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::isBuildVectorAllOnes(const SDNode *N) { 168 // Look through a bit convert. 169 while (N->getOpcode() == ISD::BITCAST) 170 N = N->getOperand(0).getNode(); 171 172 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 173 174 unsigned i = 0, e = N->getNumOperands(); 175 176 // Skip over all of the undef values. 177 while (i != e && N->getOperand(i).isUndef()) 178 ++i; 179 180 // Do not accept an all-undef vector. 181 if (i == e) return false; 182 183 // Do not accept build_vectors that aren't all constants or which have non-~0 184 // elements. We have to be a bit careful here, as the type of the constant 185 // may not be the same as the type of the vector elements due to type 186 // legalization (the elements are promoted to a legal type for the target and 187 // a vector of a type may be legal when the base element type is not). 188 // We only want to check enough bits to cover the vector elements, because 189 // we care if the resultant vector is all ones, not whether the individual 190 // constants are. 191 SDValue NotZero = N->getOperand(i); 192 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 193 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 194 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 195 return false; 196 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 197 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 198 return false; 199 } else 200 return false; 201 202 // Okay, we have at least one ~0 value, check to see if the rest match or are 203 // undefs. Even with the above element type twiddling, this should be OK, as 204 // the same type legalization should have applied to all the elements. 205 for (++i; i != e; ++i) 206 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 207 return false; 208 return true; 209 } 210 211 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 212 // Look through a bit convert. 213 while (N->getOpcode() == ISD::BITCAST) 214 N = N->getOperand(0).getNode(); 215 216 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 217 218 bool IsAllUndef = true; 219 for (const SDValue &Op : N->op_values()) { 220 if (Op.isUndef()) 221 continue; 222 IsAllUndef = false; 223 // Do not accept build_vectors that aren't all constants or which have non-0 224 // elements. We have to be a bit careful here, as the type of the constant 225 // may not be the same as the type of the vector elements due to type 226 // legalization (the elements are promoted to a legal type for the target 227 // and a vector of a type may be legal when the base element type is not). 228 // We only want to check enough bits to cover the vector elements, because 229 // we care if the resultant vector is all zeros, not whether the individual 230 // constants are. 231 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 232 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 233 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 234 return false; 235 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 236 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 237 return false; 238 } else 239 return false; 240 } 241 242 // Do not accept an all-undef vector. 243 if (IsAllUndef) 244 return false; 245 return true; 246 } 247 248 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 249 if (N->getOpcode() != ISD::BUILD_VECTOR) 250 return false; 251 252 for (const SDValue &Op : N->op_values()) { 253 if (Op.isUndef()) 254 continue; 255 if (!isa<ConstantSDNode>(Op)) 256 return false; 257 } 258 return true; 259 } 260 261 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 262 if (N->getOpcode() != ISD::BUILD_VECTOR) 263 return false; 264 265 for (const SDValue &Op : N->op_values()) { 266 if (Op.isUndef()) 267 continue; 268 if (!isa<ConstantFPSDNode>(Op)) 269 return false; 270 } 271 return true; 272 } 273 274 bool ISD::allOperandsUndef(const SDNode *N) { 275 // Return false if the node has no operands. 276 // This is "logically inconsistent" with the definition of "all" but 277 // is probably the desired behavior. 278 if (N->getNumOperands() == 0) 279 return false; 280 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 281 } 282 283 bool ISD::matchUnaryPredicate(SDValue Op, 284 std::function<bool(ConstantSDNode *)> Match, 285 bool AllowUndefs) { 286 // FIXME: Add support for scalar UNDEF cases? 287 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 288 return Match(Cst); 289 290 // FIXME: Add support for vector UNDEF cases? 291 if (ISD::BUILD_VECTOR != Op.getOpcode()) 292 return false; 293 294 EVT SVT = Op.getValueType().getScalarType(); 295 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 296 if (AllowUndefs && Op.getOperand(i).isUndef()) { 297 if (!Match(nullptr)) 298 return false; 299 continue; 300 } 301 302 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 303 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 304 return false; 305 } 306 return true; 307 } 308 309 bool ISD::matchBinaryPredicate( 310 SDValue LHS, SDValue RHS, 311 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 312 bool AllowUndefs, bool AllowTypeMismatch) { 313 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 314 return false; 315 316 // TODO: Add support for scalar UNDEF cases? 317 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 318 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 319 return Match(LHSCst, RHSCst); 320 321 // TODO: Add support for vector UNDEF cases? 322 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 323 ISD::BUILD_VECTOR != RHS.getOpcode()) 324 return false; 325 326 EVT SVT = LHS.getValueType().getScalarType(); 327 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 328 SDValue LHSOp = LHS.getOperand(i); 329 SDValue RHSOp = RHS.getOperand(i); 330 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 331 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 332 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 333 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 334 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 335 return false; 336 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 337 LHSOp.getValueType() != RHSOp.getValueType())) 338 return false; 339 if (!Match(LHSCst, RHSCst)) 340 return false; 341 } 342 return true; 343 } 344 345 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 346 switch (VecReduceOpcode) { 347 default: 348 llvm_unreachable("Expected VECREDUCE opcode"); 349 case ISD::VECREDUCE_FADD: 350 case ISD::VECREDUCE_SEQ_FADD: 351 return ISD::FADD; 352 case ISD::VECREDUCE_FMUL: 353 case ISD::VECREDUCE_SEQ_FMUL: 354 return ISD::FMUL; 355 case ISD::VECREDUCE_ADD: 356 return ISD::ADD; 357 case ISD::VECREDUCE_MUL: 358 return ISD::MUL; 359 case ISD::VECREDUCE_AND: 360 return ISD::AND; 361 case ISD::VECREDUCE_OR: 362 return ISD::OR; 363 case ISD::VECREDUCE_XOR: 364 return ISD::XOR; 365 case ISD::VECREDUCE_SMAX: 366 return ISD::SMAX; 367 case ISD::VECREDUCE_SMIN: 368 return ISD::SMIN; 369 case ISD::VECREDUCE_UMAX: 370 return ISD::UMAX; 371 case ISD::VECREDUCE_UMIN: 372 return ISD::UMIN; 373 case ISD::VECREDUCE_FMAX: 374 return ISD::FMAXNUM; 375 case ISD::VECREDUCE_FMIN: 376 return ISD::FMINNUM; 377 } 378 } 379 380 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 381 switch (ExtType) { 382 case ISD::EXTLOAD: 383 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 384 case ISD::SEXTLOAD: 385 return ISD::SIGN_EXTEND; 386 case ISD::ZEXTLOAD: 387 return ISD::ZERO_EXTEND; 388 default: 389 break; 390 } 391 392 llvm_unreachable("Invalid LoadExtType"); 393 } 394 395 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 396 // To perform this operation, we just need to swap the L and G bits of the 397 // operation. 398 unsigned OldL = (Operation >> 2) & 1; 399 unsigned OldG = (Operation >> 1) & 1; 400 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 401 (OldL << 1) | // New G bit 402 (OldG << 2)); // New L bit. 403 } 404 405 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 406 unsigned Operation = Op; 407 if (isIntegerLike) 408 Operation ^= 7; // Flip L, G, E bits, but not U. 409 else 410 Operation ^= 15; // Flip all of the condition bits. 411 412 if (Operation > ISD::SETTRUE2) 413 Operation &= ~8; // Don't let N and U bits get set. 414 415 return ISD::CondCode(Operation); 416 } 417 418 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 419 return getSetCCInverseImpl(Op, Type.isInteger()); 420 } 421 422 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 423 bool isIntegerLike) { 424 return getSetCCInverseImpl(Op, isIntegerLike); 425 } 426 427 /// For an integer comparison, return 1 if the comparison is a signed operation 428 /// and 2 if the result is an unsigned comparison. Return zero if the operation 429 /// does not depend on the sign of the input (setne and seteq). 430 static int isSignedOp(ISD::CondCode Opcode) { 431 switch (Opcode) { 432 default: llvm_unreachable("Illegal integer setcc operation!"); 433 case ISD::SETEQ: 434 case ISD::SETNE: return 0; 435 case ISD::SETLT: 436 case ISD::SETLE: 437 case ISD::SETGT: 438 case ISD::SETGE: return 1; 439 case ISD::SETULT: 440 case ISD::SETULE: 441 case ISD::SETUGT: 442 case ISD::SETUGE: return 2; 443 } 444 } 445 446 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 447 EVT Type) { 448 bool IsInteger = Type.isInteger(); 449 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 450 // Cannot fold a signed integer setcc with an unsigned integer setcc. 451 return ISD::SETCC_INVALID; 452 453 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 454 455 // If the N and U bits get set, then the resultant comparison DOES suddenly 456 // care about orderedness, and it is true when ordered. 457 if (Op > ISD::SETTRUE2) 458 Op &= ~16; // Clear the U bit if the N bit is set. 459 460 // Canonicalize illegal integer setcc's. 461 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 462 Op = ISD::SETNE; 463 464 return ISD::CondCode(Op); 465 } 466 467 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 468 EVT Type) { 469 bool IsInteger = Type.isInteger(); 470 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 471 // Cannot fold a signed setcc with an unsigned setcc. 472 return ISD::SETCC_INVALID; 473 474 // Combine all of the condition bits. 475 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 476 477 // Canonicalize illegal integer setcc's. 478 if (IsInteger) { 479 switch (Result) { 480 default: break; 481 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 482 case ISD::SETOEQ: // SETEQ & SETU[LG]E 483 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 484 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 485 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 486 } 487 } 488 489 return Result; 490 } 491 492 //===----------------------------------------------------------------------===// 493 // SDNode Profile Support 494 //===----------------------------------------------------------------------===// 495 496 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 497 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 498 ID.AddInteger(OpC); 499 } 500 501 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 502 /// solely with their pointer. 503 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 504 ID.AddPointer(VTList.VTs); 505 } 506 507 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 508 static void AddNodeIDOperands(FoldingSetNodeID &ID, 509 ArrayRef<SDValue> Ops) { 510 for (auto& Op : Ops) { 511 ID.AddPointer(Op.getNode()); 512 ID.AddInteger(Op.getResNo()); 513 } 514 } 515 516 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 517 static void AddNodeIDOperands(FoldingSetNodeID &ID, 518 ArrayRef<SDUse> Ops) { 519 for (auto& Op : Ops) { 520 ID.AddPointer(Op.getNode()); 521 ID.AddInteger(Op.getResNo()); 522 } 523 } 524 525 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 526 SDVTList VTList, ArrayRef<SDValue> OpList) { 527 AddNodeIDOpcode(ID, OpC); 528 AddNodeIDValueTypes(ID, VTList); 529 AddNodeIDOperands(ID, OpList); 530 } 531 532 /// If this is an SDNode with special info, add this info to the NodeID data. 533 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 534 switch (N->getOpcode()) { 535 case ISD::TargetExternalSymbol: 536 case ISD::ExternalSymbol: 537 case ISD::MCSymbol: 538 llvm_unreachable("Should only be used on nodes with operands"); 539 default: break; // Normal nodes don't need extra info. 540 case ISD::TargetConstant: 541 case ISD::Constant: { 542 const ConstantSDNode *C = cast<ConstantSDNode>(N); 543 ID.AddPointer(C->getConstantIntValue()); 544 ID.AddBoolean(C->isOpaque()); 545 break; 546 } 547 case ISD::TargetConstantFP: 548 case ISD::ConstantFP: 549 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 550 break; 551 case ISD::TargetGlobalAddress: 552 case ISD::GlobalAddress: 553 case ISD::TargetGlobalTLSAddress: 554 case ISD::GlobalTLSAddress: { 555 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 556 ID.AddPointer(GA->getGlobal()); 557 ID.AddInteger(GA->getOffset()); 558 ID.AddInteger(GA->getTargetFlags()); 559 break; 560 } 561 case ISD::BasicBlock: 562 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 563 break; 564 case ISD::Register: 565 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 566 break; 567 case ISD::RegisterMask: 568 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 569 break; 570 case ISD::SRCVALUE: 571 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 572 break; 573 case ISD::FrameIndex: 574 case ISD::TargetFrameIndex: 575 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 576 break; 577 case ISD::LIFETIME_START: 578 case ISD::LIFETIME_END: 579 if (cast<LifetimeSDNode>(N)->hasOffset()) { 580 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 581 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 582 } 583 break; 584 case ISD::PSEUDO_PROBE: 585 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 586 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 587 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 588 break; 589 case ISD::JumpTable: 590 case ISD::TargetJumpTable: 591 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 592 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 593 break; 594 case ISD::ConstantPool: 595 case ISD::TargetConstantPool: { 596 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 597 ID.AddInteger(CP->getAlign().value()); 598 ID.AddInteger(CP->getOffset()); 599 if (CP->isMachineConstantPoolEntry()) 600 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 601 else 602 ID.AddPointer(CP->getConstVal()); 603 ID.AddInteger(CP->getTargetFlags()); 604 break; 605 } 606 case ISD::TargetIndex: { 607 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 608 ID.AddInteger(TI->getIndex()); 609 ID.AddInteger(TI->getOffset()); 610 ID.AddInteger(TI->getTargetFlags()); 611 break; 612 } 613 case ISD::LOAD: { 614 const LoadSDNode *LD = cast<LoadSDNode>(N); 615 ID.AddInteger(LD->getMemoryVT().getRawBits()); 616 ID.AddInteger(LD->getRawSubclassData()); 617 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 618 break; 619 } 620 case ISD::STORE: { 621 const StoreSDNode *ST = cast<StoreSDNode>(N); 622 ID.AddInteger(ST->getMemoryVT().getRawBits()); 623 ID.AddInteger(ST->getRawSubclassData()); 624 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 625 break; 626 } 627 case ISD::MLOAD: { 628 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 629 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 630 ID.AddInteger(MLD->getRawSubclassData()); 631 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 632 break; 633 } 634 case ISD::MSTORE: { 635 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 636 ID.AddInteger(MST->getMemoryVT().getRawBits()); 637 ID.AddInteger(MST->getRawSubclassData()); 638 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 639 break; 640 } 641 case ISD::MGATHER: { 642 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 643 ID.AddInteger(MG->getMemoryVT().getRawBits()); 644 ID.AddInteger(MG->getRawSubclassData()); 645 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 646 break; 647 } 648 case ISD::MSCATTER: { 649 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 650 ID.AddInteger(MS->getMemoryVT().getRawBits()); 651 ID.AddInteger(MS->getRawSubclassData()); 652 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 653 break; 654 } 655 case ISD::ATOMIC_CMP_SWAP: 656 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 657 case ISD::ATOMIC_SWAP: 658 case ISD::ATOMIC_LOAD_ADD: 659 case ISD::ATOMIC_LOAD_SUB: 660 case ISD::ATOMIC_LOAD_AND: 661 case ISD::ATOMIC_LOAD_CLR: 662 case ISD::ATOMIC_LOAD_OR: 663 case ISD::ATOMIC_LOAD_XOR: 664 case ISD::ATOMIC_LOAD_NAND: 665 case ISD::ATOMIC_LOAD_MIN: 666 case ISD::ATOMIC_LOAD_MAX: 667 case ISD::ATOMIC_LOAD_UMIN: 668 case ISD::ATOMIC_LOAD_UMAX: 669 case ISD::ATOMIC_LOAD: 670 case ISD::ATOMIC_STORE: { 671 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 672 ID.AddInteger(AT->getMemoryVT().getRawBits()); 673 ID.AddInteger(AT->getRawSubclassData()); 674 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 675 break; 676 } 677 case ISD::PREFETCH: { 678 const MemSDNode *PF = cast<MemSDNode>(N); 679 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 680 break; 681 } 682 case ISD::VECTOR_SHUFFLE: { 683 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 684 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 685 i != e; ++i) 686 ID.AddInteger(SVN->getMaskElt(i)); 687 break; 688 } 689 case ISD::TargetBlockAddress: 690 case ISD::BlockAddress: { 691 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 692 ID.AddPointer(BA->getBlockAddress()); 693 ID.AddInteger(BA->getOffset()); 694 ID.AddInteger(BA->getTargetFlags()); 695 break; 696 } 697 } // end switch (N->getOpcode()) 698 699 // Target specific memory nodes could also have address spaces to check. 700 if (N->isTargetMemoryOpcode()) 701 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 702 } 703 704 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 705 /// data. 706 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 707 AddNodeIDOpcode(ID, N->getOpcode()); 708 // Add the return value info. 709 AddNodeIDValueTypes(ID, N->getVTList()); 710 // Add the operand info. 711 AddNodeIDOperands(ID, N->ops()); 712 713 // Handle SDNode leafs with special info. 714 AddNodeIDCustom(ID, N); 715 } 716 717 //===----------------------------------------------------------------------===// 718 // SelectionDAG Class 719 //===----------------------------------------------------------------------===// 720 721 /// doNotCSE - Return true if CSE should not be performed for this node. 722 static bool doNotCSE(SDNode *N) { 723 if (N->getValueType(0) == MVT::Glue) 724 return true; // Never CSE anything that produces a flag. 725 726 switch (N->getOpcode()) { 727 default: break; 728 case ISD::HANDLENODE: 729 case ISD::EH_LABEL: 730 return true; // Never CSE these nodes. 731 } 732 733 // Check that remaining values produced are not flags. 734 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 735 if (N->getValueType(i) == MVT::Glue) 736 return true; // Never CSE anything that produces a flag. 737 738 return false; 739 } 740 741 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 742 /// SelectionDAG. 743 void SelectionDAG::RemoveDeadNodes() { 744 // Create a dummy node (which is not added to allnodes), that adds a reference 745 // to the root node, preventing it from being deleted. 746 HandleSDNode Dummy(getRoot()); 747 748 SmallVector<SDNode*, 128> DeadNodes; 749 750 // Add all obviously-dead nodes to the DeadNodes worklist. 751 for (SDNode &Node : allnodes()) 752 if (Node.use_empty()) 753 DeadNodes.push_back(&Node); 754 755 RemoveDeadNodes(DeadNodes); 756 757 // If the root changed (e.g. it was a dead load, update the root). 758 setRoot(Dummy.getValue()); 759 } 760 761 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 762 /// given list, and any nodes that become unreachable as a result. 763 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 764 765 // Process the worklist, deleting the nodes and adding their uses to the 766 // worklist. 767 while (!DeadNodes.empty()) { 768 SDNode *N = DeadNodes.pop_back_val(); 769 // Skip to next node if we've already managed to delete the node. This could 770 // happen if replacing a node causes a node previously added to the node to 771 // be deleted. 772 if (N->getOpcode() == ISD::DELETED_NODE) 773 continue; 774 775 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 776 DUL->NodeDeleted(N, nullptr); 777 778 // Take the node out of the appropriate CSE map. 779 RemoveNodeFromCSEMaps(N); 780 781 // Next, brutally remove the operand list. This is safe to do, as there are 782 // no cycles in the graph. 783 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 784 SDUse &Use = *I++; 785 SDNode *Operand = Use.getNode(); 786 Use.set(SDValue()); 787 788 // Now that we removed this operand, see if there are no uses of it left. 789 if (Operand->use_empty()) 790 DeadNodes.push_back(Operand); 791 } 792 793 DeallocateNode(N); 794 } 795 } 796 797 void SelectionDAG::RemoveDeadNode(SDNode *N){ 798 SmallVector<SDNode*, 16> DeadNodes(1, N); 799 800 // Create a dummy node that adds a reference to the root node, preventing 801 // it from being deleted. (This matters if the root is an operand of the 802 // dead node.) 803 HandleSDNode Dummy(getRoot()); 804 805 RemoveDeadNodes(DeadNodes); 806 } 807 808 void SelectionDAG::DeleteNode(SDNode *N) { 809 // First take this out of the appropriate CSE map. 810 RemoveNodeFromCSEMaps(N); 811 812 // Finally, remove uses due to operands of this node, remove from the 813 // AllNodes list, and delete the node. 814 DeleteNodeNotInCSEMaps(N); 815 } 816 817 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 818 assert(N->getIterator() != AllNodes.begin() && 819 "Cannot delete the entry node!"); 820 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 821 822 // Drop all of the operands and decrement used node's use counts. 823 N->DropOperands(); 824 825 DeallocateNode(N); 826 } 827 828 void SDDbgInfo::erase(const SDNode *Node) { 829 DbgValMapType::iterator I = DbgValMap.find(Node); 830 if (I == DbgValMap.end()) 831 return; 832 for (auto &Val: I->second) 833 Val->setIsInvalidated(); 834 DbgValMap.erase(I); 835 } 836 837 void SelectionDAG::DeallocateNode(SDNode *N) { 838 // If we have operands, deallocate them. 839 removeOperands(N); 840 841 NodeAllocator.Deallocate(AllNodes.remove(N)); 842 843 // Set the opcode to DELETED_NODE to help catch bugs when node 844 // memory is reallocated. 845 // FIXME: There are places in SDag that have grown a dependency on the opcode 846 // value in the released node. 847 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 848 N->NodeType = ISD::DELETED_NODE; 849 850 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 851 // them and forget about that node. 852 DbgInfo->erase(N); 853 } 854 855 #ifndef NDEBUG 856 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 857 static void VerifySDNode(SDNode *N) { 858 switch (N->getOpcode()) { 859 default: 860 break; 861 case ISD::BUILD_PAIR: { 862 EVT VT = N->getValueType(0); 863 assert(N->getNumValues() == 1 && "Too many results!"); 864 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 865 "Wrong return type!"); 866 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 867 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 868 "Mismatched operand types!"); 869 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 870 "Wrong operand type!"); 871 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 872 "Wrong return type size"); 873 break; 874 } 875 case ISD::BUILD_VECTOR: { 876 assert(N->getNumValues() == 1 && "Too many results!"); 877 assert(N->getValueType(0).isVector() && "Wrong return type!"); 878 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 879 "Wrong number of operands!"); 880 EVT EltVT = N->getValueType(0).getVectorElementType(); 881 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) { 882 assert((I->getValueType() == EltVT || 883 (EltVT.isInteger() && I->getValueType().isInteger() && 884 EltVT.bitsLE(I->getValueType()))) && 885 "Wrong operand type!"); 886 assert(I->getValueType() == N->getOperand(0).getValueType() && 887 "Operands must all have the same type"); 888 } 889 break; 890 } 891 } 892 } 893 #endif // NDEBUG 894 895 /// Insert a newly allocated node into the DAG. 896 /// 897 /// Handles insertion into the all nodes list and CSE map, as well as 898 /// verification and other common operations when a new node is allocated. 899 void SelectionDAG::InsertNode(SDNode *N) { 900 AllNodes.push_back(N); 901 #ifndef NDEBUG 902 N->PersistentId = NextPersistentId++; 903 VerifySDNode(N); 904 #endif 905 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 906 DUL->NodeInserted(N); 907 } 908 909 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 910 /// correspond to it. This is useful when we're about to delete or repurpose 911 /// the node. We don't want future request for structurally identical nodes 912 /// to return N anymore. 913 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 914 bool Erased = false; 915 switch (N->getOpcode()) { 916 case ISD::HANDLENODE: return false; // noop. 917 case ISD::CONDCODE: 918 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 919 "Cond code doesn't exist!"); 920 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 921 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 922 break; 923 case ISD::ExternalSymbol: 924 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 925 break; 926 case ISD::TargetExternalSymbol: { 927 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 928 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 929 ESN->getSymbol(), ESN->getTargetFlags())); 930 break; 931 } 932 case ISD::MCSymbol: { 933 auto *MCSN = cast<MCSymbolSDNode>(N); 934 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 935 break; 936 } 937 case ISD::VALUETYPE: { 938 EVT VT = cast<VTSDNode>(N)->getVT(); 939 if (VT.isExtended()) { 940 Erased = ExtendedValueTypeNodes.erase(VT); 941 } else { 942 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 943 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 944 } 945 break; 946 } 947 default: 948 // Remove it from the CSE Map. 949 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 950 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 951 Erased = CSEMap.RemoveNode(N); 952 break; 953 } 954 #ifndef NDEBUG 955 // Verify that the node was actually in one of the CSE maps, unless it has a 956 // flag result (which cannot be CSE'd) or is one of the special cases that are 957 // not subject to CSE. 958 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 959 !N->isMachineOpcode() && !doNotCSE(N)) { 960 N->dump(this); 961 dbgs() << "\n"; 962 llvm_unreachable("Node is not in map!"); 963 } 964 #endif 965 return Erased; 966 } 967 968 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 969 /// maps and modified in place. Add it back to the CSE maps, unless an identical 970 /// node already exists, in which case transfer all its users to the existing 971 /// node. This transfer can potentially trigger recursive merging. 972 void 973 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 974 // For node types that aren't CSE'd, just act as if no identical node 975 // already exists. 976 if (!doNotCSE(N)) { 977 SDNode *Existing = CSEMap.GetOrInsertNode(N); 978 if (Existing != N) { 979 // If there was already an existing matching node, use ReplaceAllUsesWith 980 // to replace the dead one with the existing one. This can cause 981 // recursive merging of other unrelated nodes down the line. 982 ReplaceAllUsesWith(N, Existing); 983 984 // N is now dead. Inform the listeners and delete it. 985 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 986 DUL->NodeDeleted(N, Existing); 987 DeleteNodeNotInCSEMaps(N); 988 return; 989 } 990 } 991 992 // If the node doesn't already exist, we updated it. Inform listeners. 993 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 994 DUL->NodeUpdated(N); 995 } 996 997 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 998 /// were replaced with those specified. If this node is never memoized, 999 /// return null, otherwise return a pointer to the slot it would take. If a 1000 /// node already exists with these operands, the slot will be non-null. 1001 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1002 void *&InsertPos) { 1003 if (doNotCSE(N)) 1004 return nullptr; 1005 1006 SDValue Ops[] = { Op }; 1007 FoldingSetNodeID ID; 1008 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1009 AddNodeIDCustom(ID, N); 1010 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1011 if (Node) 1012 Node->intersectFlagsWith(N->getFlags()); 1013 return Node; 1014 } 1015 1016 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1017 /// were replaced with those specified. If this node is never memoized, 1018 /// return null, otherwise return a pointer to the slot it would take. If a 1019 /// node already exists with these operands, the slot will be non-null. 1020 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1021 SDValue Op1, SDValue Op2, 1022 void *&InsertPos) { 1023 if (doNotCSE(N)) 1024 return nullptr; 1025 1026 SDValue Ops[] = { Op1, Op2 }; 1027 FoldingSetNodeID ID; 1028 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1029 AddNodeIDCustom(ID, N); 1030 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1031 if (Node) 1032 Node->intersectFlagsWith(N->getFlags()); 1033 return Node; 1034 } 1035 1036 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1037 /// were replaced with those specified. If this node is never memoized, 1038 /// return null, otherwise return a pointer to the slot it would take. If a 1039 /// node already exists with these operands, the slot will be non-null. 1040 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1041 void *&InsertPos) { 1042 if (doNotCSE(N)) 1043 return nullptr; 1044 1045 FoldingSetNodeID ID; 1046 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1047 AddNodeIDCustom(ID, N); 1048 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1049 if (Node) 1050 Node->intersectFlagsWith(N->getFlags()); 1051 return Node; 1052 } 1053 1054 Align SelectionDAG::getEVTAlign(EVT VT) const { 1055 Type *Ty = VT == MVT::iPTR ? 1056 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1057 VT.getTypeForEVT(*getContext()); 1058 1059 return getDataLayout().getABITypeAlign(Ty); 1060 } 1061 1062 // EntryNode could meaningfully have debug info if we can find it... 1063 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1064 : TM(tm), OptLevel(OL), 1065 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1066 Root(getEntryNode()) { 1067 InsertNode(&EntryNode); 1068 DbgInfo = new SDDbgInfo(); 1069 } 1070 1071 void SelectionDAG::init(MachineFunction &NewMF, 1072 OptimizationRemarkEmitter &NewORE, 1073 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1074 LegacyDivergenceAnalysis * Divergence, 1075 ProfileSummaryInfo *PSIin, 1076 BlockFrequencyInfo *BFIin) { 1077 MF = &NewMF; 1078 SDAGISelPass = PassPtr; 1079 ORE = &NewORE; 1080 TLI = getSubtarget().getTargetLowering(); 1081 TSI = getSubtarget().getSelectionDAGInfo(); 1082 LibInfo = LibraryInfo; 1083 Context = &MF->getFunction().getContext(); 1084 DA = Divergence; 1085 PSI = PSIin; 1086 BFI = BFIin; 1087 } 1088 1089 SelectionDAG::~SelectionDAG() { 1090 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1091 allnodes_clear(); 1092 OperandRecycler.clear(OperandAllocator); 1093 delete DbgInfo; 1094 } 1095 1096 bool SelectionDAG::shouldOptForSize() const { 1097 return MF->getFunction().hasOptSize() || 1098 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1099 } 1100 1101 void SelectionDAG::allnodes_clear() { 1102 assert(&*AllNodes.begin() == &EntryNode); 1103 AllNodes.remove(AllNodes.begin()); 1104 while (!AllNodes.empty()) 1105 DeallocateNode(&AllNodes.front()); 1106 #ifndef NDEBUG 1107 NextPersistentId = 0; 1108 #endif 1109 } 1110 1111 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1112 void *&InsertPos) { 1113 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1114 if (N) { 1115 switch (N->getOpcode()) { 1116 default: break; 1117 case ISD::Constant: 1118 case ISD::ConstantFP: 1119 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1120 "debug location. Use another overload."); 1121 } 1122 } 1123 return N; 1124 } 1125 1126 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1127 const SDLoc &DL, void *&InsertPos) { 1128 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1129 if (N) { 1130 switch (N->getOpcode()) { 1131 case ISD::Constant: 1132 case ISD::ConstantFP: 1133 // Erase debug location from the node if the node is used at several 1134 // different places. Do not propagate one location to all uses as it 1135 // will cause a worse single stepping debugging experience. 1136 if (N->getDebugLoc() != DL.getDebugLoc()) 1137 N->setDebugLoc(DebugLoc()); 1138 break; 1139 default: 1140 // When the node's point of use is located earlier in the instruction 1141 // sequence than its prior point of use, update its debug info to the 1142 // earlier location. 1143 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1144 N->setDebugLoc(DL.getDebugLoc()); 1145 break; 1146 } 1147 } 1148 return N; 1149 } 1150 1151 void SelectionDAG::clear() { 1152 allnodes_clear(); 1153 OperandRecycler.clear(OperandAllocator); 1154 OperandAllocator.Reset(); 1155 CSEMap.clear(); 1156 1157 ExtendedValueTypeNodes.clear(); 1158 ExternalSymbols.clear(); 1159 TargetExternalSymbols.clear(); 1160 MCSymbols.clear(); 1161 SDCallSiteDbgInfo.clear(); 1162 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1163 static_cast<CondCodeSDNode*>(nullptr)); 1164 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1165 static_cast<SDNode*>(nullptr)); 1166 1167 EntryNode.UseList = nullptr; 1168 InsertNode(&EntryNode); 1169 Root = getEntryNode(); 1170 DbgInfo->clear(); 1171 } 1172 1173 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1174 return VT.bitsGT(Op.getValueType()) 1175 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1176 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1177 } 1178 1179 std::pair<SDValue, SDValue> 1180 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1181 const SDLoc &DL, EVT VT) { 1182 assert(!VT.bitsEq(Op.getValueType()) && 1183 "Strict no-op FP extend/round not allowed."); 1184 SDValue Res = 1185 VT.bitsGT(Op.getValueType()) 1186 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1187 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1188 {Chain, Op, getIntPtrConstant(0, DL)}); 1189 1190 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1191 } 1192 1193 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1194 return VT.bitsGT(Op.getValueType()) ? 1195 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1196 getNode(ISD::TRUNCATE, DL, VT, Op); 1197 } 1198 1199 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1200 return VT.bitsGT(Op.getValueType()) ? 1201 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1202 getNode(ISD::TRUNCATE, DL, VT, Op); 1203 } 1204 1205 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1206 return VT.bitsGT(Op.getValueType()) ? 1207 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1208 getNode(ISD::TRUNCATE, DL, VT, Op); 1209 } 1210 1211 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1212 EVT OpVT) { 1213 if (VT.bitsLE(Op.getValueType())) 1214 return getNode(ISD::TRUNCATE, SL, VT, Op); 1215 1216 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1217 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1218 } 1219 1220 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1221 EVT OpVT = Op.getValueType(); 1222 assert(VT.isInteger() && OpVT.isInteger() && 1223 "Cannot getZeroExtendInReg FP types"); 1224 assert(VT.isVector() == OpVT.isVector() && 1225 "getZeroExtendInReg type should be vector iff the operand " 1226 "type is vector!"); 1227 assert((!VT.isVector() || 1228 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1229 "Vector element counts must match in getZeroExtendInReg"); 1230 assert(VT.bitsLE(OpVT) && "Not extending!"); 1231 if (OpVT == VT) 1232 return Op; 1233 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1234 VT.getScalarSizeInBits()); 1235 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1236 } 1237 1238 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1239 // Only unsigned pointer semantics are supported right now. In the future this 1240 // might delegate to TLI to check pointer signedness. 1241 return getZExtOrTrunc(Op, DL, VT); 1242 } 1243 1244 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1245 // Only unsigned pointer semantics are supported right now. In the future this 1246 // might delegate to TLI to check pointer signedness. 1247 return getZeroExtendInReg(Op, DL, VT); 1248 } 1249 1250 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1251 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1252 EVT EltVT = VT.getScalarType(); 1253 SDValue NegOne = 1254 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1255 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1256 } 1257 1258 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1259 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1260 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1261 } 1262 1263 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1264 EVT OpVT) { 1265 if (!V) 1266 return getConstant(0, DL, VT); 1267 1268 switch (TLI->getBooleanContents(OpVT)) { 1269 case TargetLowering::ZeroOrOneBooleanContent: 1270 case TargetLowering::UndefinedBooleanContent: 1271 return getConstant(1, DL, VT); 1272 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1273 return getAllOnesConstant(DL, VT); 1274 } 1275 llvm_unreachable("Unexpected boolean content enum!"); 1276 } 1277 1278 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1279 bool isT, bool isO) { 1280 EVT EltVT = VT.getScalarType(); 1281 assert((EltVT.getSizeInBits() >= 64 || 1282 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1283 "getConstant with a uint64_t value that doesn't fit in the type!"); 1284 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1285 } 1286 1287 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1288 bool isT, bool isO) { 1289 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1290 } 1291 1292 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1293 EVT VT, bool isT, bool isO) { 1294 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1295 1296 EVT EltVT = VT.getScalarType(); 1297 const ConstantInt *Elt = &Val; 1298 1299 // In some cases the vector type is legal but the element type is illegal and 1300 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1301 // inserted value (the type does not need to match the vector element type). 1302 // Any extra bits introduced will be truncated away. 1303 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1304 TargetLowering::TypePromoteInteger) { 1305 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1306 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1307 Elt = ConstantInt::get(*getContext(), NewVal); 1308 } 1309 // In other cases the element type is illegal and needs to be expanded, for 1310 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1311 // the value into n parts and use a vector type with n-times the elements. 1312 // Then bitcast to the type requested. 1313 // Legalizing constants too early makes the DAGCombiner's job harder so we 1314 // only legalize if the DAG tells us we must produce legal types. 1315 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1316 TLI->getTypeAction(*getContext(), EltVT) == 1317 TargetLowering::TypeExpandInteger) { 1318 const APInt &NewVal = Elt->getValue(); 1319 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1320 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1321 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1322 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1323 1324 // Check the temporary vector is the correct size. If this fails then 1325 // getTypeToTransformTo() probably returned a type whose size (in bits) 1326 // isn't a power-of-2 factor of the requested type size. 1327 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1328 1329 SmallVector<SDValue, 2> EltParts; 1330 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1331 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits) 1332 .zextOrTrunc(ViaEltSizeInBits), DL, 1333 ViaEltVT, isT, isO)); 1334 } 1335 1336 // EltParts is currently in little endian order. If we actually want 1337 // big-endian order then reverse it now. 1338 if (getDataLayout().isBigEndian()) 1339 std::reverse(EltParts.begin(), EltParts.end()); 1340 1341 // The elements must be reversed when the element order is different 1342 // to the endianness of the elements (because the BITCAST is itself a 1343 // vector shuffle in this situation). However, we do not need any code to 1344 // perform this reversal because getConstant() is producing a vector 1345 // splat. 1346 // This situation occurs in MIPS MSA. 1347 1348 SmallVector<SDValue, 8> Ops; 1349 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1350 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end()); 1351 1352 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1353 return V; 1354 } 1355 1356 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1357 "APInt size does not match type size!"); 1358 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1359 FoldingSetNodeID ID; 1360 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1361 ID.AddPointer(Elt); 1362 ID.AddBoolean(isO); 1363 void *IP = nullptr; 1364 SDNode *N = nullptr; 1365 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1366 if (!VT.isVector()) 1367 return SDValue(N, 0); 1368 1369 if (!N) { 1370 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1371 CSEMap.InsertNode(N, IP); 1372 InsertNode(N); 1373 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1374 } 1375 1376 SDValue Result(N, 0); 1377 if (VT.isScalableVector()) 1378 Result = getSplatVector(VT, DL, Result); 1379 else if (VT.isVector()) 1380 Result = getSplatBuildVector(VT, DL, Result); 1381 1382 return Result; 1383 } 1384 1385 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1386 bool isTarget) { 1387 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1388 } 1389 1390 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1391 const SDLoc &DL, bool LegalTypes) { 1392 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1393 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1394 return getConstant(Val, DL, ShiftVT); 1395 } 1396 1397 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1398 bool isTarget) { 1399 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1400 } 1401 1402 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1403 bool isTarget) { 1404 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1405 } 1406 1407 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1408 EVT VT, bool isTarget) { 1409 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1410 1411 EVT EltVT = VT.getScalarType(); 1412 1413 // Do the map lookup using the actual bit pattern for the floating point 1414 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1415 // we don't have issues with SNANs. 1416 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1417 FoldingSetNodeID ID; 1418 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1419 ID.AddPointer(&V); 1420 void *IP = nullptr; 1421 SDNode *N = nullptr; 1422 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1423 if (!VT.isVector()) 1424 return SDValue(N, 0); 1425 1426 if (!N) { 1427 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1428 CSEMap.InsertNode(N, IP); 1429 InsertNode(N); 1430 } 1431 1432 SDValue Result(N, 0); 1433 if (VT.isScalableVector()) 1434 Result = getSplatVector(VT, DL, Result); 1435 else if (VT.isVector()) 1436 Result = getSplatBuildVector(VT, DL, Result); 1437 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1438 return Result; 1439 } 1440 1441 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1442 bool isTarget) { 1443 EVT EltVT = VT.getScalarType(); 1444 if (EltVT == MVT::f32) 1445 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1446 else if (EltVT == MVT::f64) 1447 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1448 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1449 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1450 bool Ignored; 1451 APFloat APF = APFloat(Val); 1452 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1453 &Ignored); 1454 return getConstantFP(APF, DL, VT, isTarget); 1455 } else 1456 llvm_unreachable("Unsupported type in getConstantFP"); 1457 } 1458 1459 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1460 EVT VT, int64_t Offset, bool isTargetGA, 1461 unsigned TargetFlags) { 1462 assert((TargetFlags == 0 || isTargetGA) && 1463 "Cannot set target flags on target-independent globals"); 1464 1465 // Truncate (with sign-extension) the offset value to the pointer size. 1466 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1467 if (BitWidth < 64) 1468 Offset = SignExtend64(Offset, BitWidth); 1469 1470 unsigned Opc; 1471 if (GV->isThreadLocal()) 1472 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1473 else 1474 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1475 1476 FoldingSetNodeID ID; 1477 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1478 ID.AddPointer(GV); 1479 ID.AddInteger(Offset); 1480 ID.AddInteger(TargetFlags); 1481 void *IP = nullptr; 1482 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1483 return SDValue(E, 0); 1484 1485 auto *N = newSDNode<GlobalAddressSDNode>( 1486 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1487 CSEMap.InsertNode(N, IP); 1488 InsertNode(N); 1489 return SDValue(N, 0); 1490 } 1491 1492 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1493 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1494 FoldingSetNodeID ID; 1495 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1496 ID.AddInteger(FI); 1497 void *IP = nullptr; 1498 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1499 return SDValue(E, 0); 1500 1501 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1502 CSEMap.InsertNode(N, IP); 1503 InsertNode(N); 1504 return SDValue(N, 0); 1505 } 1506 1507 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1508 unsigned TargetFlags) { 1509 assert((TargetFlags == 0 || isTarget) && 1510 "Cannot set target flags on target-independent jump tables"); 1511 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1512 FoldingSetNodeID ID; 1513 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1514 ID.AddInteger(JTI); 1515 ID.AddInteger(TargetFlags); 1516 void *IP = nullptr; 1517 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1518 return SDValue(E, 0); 1519 1520 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1521 CSEMap.InsertNode(N, IP); 1522 InsertNode(N); 1523 return SDValue(N, 0); 1524 } 1525 1526 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1527 MaybeAlign Alignment, int Offset, 1528 bool isTarget, unsigned TargetFlags) { 1529 assert((TargetFlags == 0 || isTarget) && 1530 "Cannot set target flags on target-independent globals"); 1531 if (!Alignment) 1532 Alignment = shouldOptForSize() 1533 ? getDataLayout().getABITypeAlign(C->getType()) 1534 : getDataLayout().getPrefTypeAlign(C->getType()); 1535 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1536 FoldingSetNodeID ID; 1537 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1538 ID.AddInteger(Alignment->value()); 1539 ID.AddInteger(Offset); 1540 ID.AddPointer(C); 1541 ID.AddInteger(TargetFlags); 1542 void *IP = nullptr; 1543 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1544 return SDValue(E, 0); 1545 1546 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1547 TargetFlags); 1548 CSEMap.InsertNode(N, IP); 1549 InsertNode(N); 1550 SDValue V = SDValue(N, 0); 1551 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1552 return V; 1553 } 1554 1555 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1556 MaybeAlign Alignment, int Offset, 1557 bool isTarget, unsigned TargetFlags) { 1558 assert((TargetFlags == 0 || isTarget) && 1559 "Cannot set target flags on target-independent globals"); 1560 if (!Alignment) 1561 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1562 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1563 FoldingSetNodeID ID; 1564 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1565 ID.AddInteger(Alignment->value()); 1566 ID.AddInteger(Offset); 1567 C->addSelectionDAGCSEId(ID); 1568 ID.AddInteger(TargetFlags); 1569 void *IP = nullptr; 1570 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1571 return SDValue(E, 0); 1572 1573 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1574 TargetFlags); 1575 CSEMap.InsertNode(N, IP); 1576 InsertNode(N); 1577 return SDValue(N, 0); 1578 } 1579 1580 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1581 unsigned TargetFlags) { 1582 FoldingSetNodeID ID; 1583 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1584 ID.AddInteger(Index); 1585 ID.AddInteger(Offset); 1586 ID.AddInteger(TargetFlags); 1587 void *IP = nullptr; 1588 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1589 return SDValue(E, 0); 1590 1591 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1592 CSEMap.InsertNode(N, IP); 1593 InsertNode(N); 1594 return SDValue(N, 0); 1595 } 1596 1597 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1598 FoldingSetNodeID ID; 1599 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1600 ID.AddPointer(MBB); 1601 void *IP = nullptr; 1602 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1603 return SDValue(E, 0); 1604 1605 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1606 CSEMap.InsertNode(N, IP); 1607 InsertNode(N); 1608 return SDValue(N, 0); 1609 } 1610 1611 SDValue SelectionDAG::getValueType(EVT VT) { 1612 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1613 ValueTypeNodes.size()) 1614 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1615 1616 SDNode *&N = VT.isExtended() ? 1617 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1618 1619 if (N) return SDValue(N, 0); 1620 N = newSDNode<VTSDNode>(VT); 1621 InsertNode(N); 1622 return SDValue(N, 0); 1623 } 1624 1625 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1626 SDNode *&N = ExternalSymbols[Sym]; 1627 if (N) return SDValue(N, 0); 1628 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1629 InsertNode(N); 1630 return SDValue(N, 0); 1631 } 1632 1633 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1634 SDNode *&N = MCSymbols[Sym]; 1635 if (N) 1636 return SDValue(N, 0); 1637 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1638 InsertNode(N); 1639 return SDValue(N, 0); 1640 } 1641 1642 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1643 unsigned TargetFlags) { 1644 SDNode *&N = 1645 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1646 if (N) return SDValue(N, 0); 1647 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1648 InsertNode(N); 1649 return SDValue(N, 0); 1650 } 1651 1652 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1653 if ((unsigned)Cond >= CondCodeNodes.size()) 1654 CondCodeNodes.resize(Cond+1); 1655 1656 if (!CondCodeNodes[Cond]) { 1657 auto *N = newSDNode<CondCodeSDNode>(Cond); 1658 CondCodeNodes[Cond] = N; 1659 InsertNode(N); 1660 } 1661 1662 return SDValue(CondCodeNodes[Cond], 0); 1663 } 1664 1665 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1666 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1667 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1668 std::swap(N1, N2); 1669 ShuffleVectorSDNode::commuteMask(M); 1670 } 1671 1672 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1673 SDValue N2, ArrayRef<int> Mask) { 1674 assert(VT.getVectorNumElements() == Mask.size() && 1675 "Must have the same number of vector elements as mask elements!"); 1676 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1677 "Invalid VECTOR_SHUFFLE"); 1678 1679 // Canonicalize shuffle undef, undef -> undef 1680 if (N1.isUndef() && N2.isUndef()) 1681 return getUNDEF(VT); 1682 1683 // Validate that all indices in Mask are within the range of the elements 1684 // input to the shuffle. 1685 int NElts = Mask.size(); 1686 assert(llvm::all_of(Mask, 1687 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1688 "Index out of range"); 1689 1690 // Copy the mask so we can do any needed cleanup. 1691 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1692 1693 // Canonicalize shuffle v, v -> v, undef 1694 if (N1 == N2) { 1695 N2 = getUNDEF(VT); 1696 for (int i = 0; i != NElts; ++i) 1697 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1698 } 1699 1700 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1701 if (N1.isUndef()) 1702 commuteShuffle(N1, N2, MaskVec); 1703 1704 if (TLI->hasVectorBlend()) { 1705 // If shuffling a splat, try to blend the splat instead. We do this here so 1706 // that even when this arises during lowering we don't have to re-handle it. 1707 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1708 BitVector UndefElements; 1709 SDValue Splat = BV->getSplatValue(&UndefElements); 1710 if (!Splat) 1711 return; 1712 1713 for (int i = 0; i < NElts; ++i) { 1714 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1715 continue; 1716 1717 // If this input comes from undef, mark it as such. 1718 if (UndefElements[MaskVec[i] - Offset]) { 1719 MaskVec[i] = -1; 1720 continue; 1721 } 1722 1723 // If we can blend a non-undef lane, use that instead. 1724 if (!UndefElements[i]) 1725 MaskVec[i] = i + Offset; 1726 } 1727 }; 1728 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1729 BlendSplat(N1BV, 0); 1730 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1731 BlendSplat(N2BV, NElts); 1732 } 1733 1734 // Canonicalize all index into lhs, -> shuffle lhs, undef 1735 // Canonicalize all index into rhs, -> shuffle rhs, undef 1736 bool AllLHS = true, AllRHS = true; 1737 bool N2Undef = N2.isUndef(); 1738 for (int i = 0; i != NElts; ++i) { 1739 if (MaskVec[i] >= NElts) { 1740 if (N2Undef) 1741 MaskVec[i] = -1; 1742 else 1743 AllLHS = false; 1744 } else if (MaskVec[i] >= 0) { 1745 AllRHS = false; 1746 } 1747 } 1748 if (AllLHS && AllRHS) 1749 return getUNDEF(VT); 1750 if (AllLHS && !N2Undef) 1751 N2 = getUNDEF(VT); 1752 if (AllRHS) { 1753 N1 = getUNDEF(VT); 1754 commuteShuffle(N1, N2, MaskVec); 1755 } 1756 // Reset our undef status after accounting for the mask. 1757 N2Undef = N2.isUndef(); 1758 // Re-check whether both sides ended up undef. 1759 if (N1.isUndef() && N2Undef) 1760 return getUNDEF(VT); 1761 1762 // If Identity shuffle return that node. 1763 bool Identity = true, AllSame = true; 1764 for (int i = 0; i != NElts; ++i) { 1765 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1766 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1767 } 1768 if (Identity && NElts) 1769 return N1; 1770 1771 // Shuffling a constant splat doesn't change the result. 1772 if (N2Undef) { 1773 SDValue V = N1; 1774 1775 // Look through any bitcasts. We check that these don't change the number 1776 // (and size) of elements and just changes their types. 1777 while (V.getOpcode() == ISD::BITCAST) 1778 V = V->getOperand(0); 1779 1780 // A splat should always show up as a build vector node. 1781 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1782 BitVector UndefElements; 1783 SDValue Splat = BV->getSplatValue(&UndefElements); 1784 // If this is a splat of an undef, shuffling it is also undef. 1785 if (Splat && Splat.isUndef()) 1786 return getUNDEF(VT); 1787 1788 bool SameNumElts = 1789 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1790 1791 // We only have a splat which can skip shuffles if there is a splatted 1792 // value and no undef lanes rearranged by the shuffle. 1793 if (Splat && UndefElements.none()) { 1794 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1795 // number of elements match or the value splatted is a zero constant. 1796 if (SameNumElts) 1797 return N1; 1798 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1799 if (C->isNullValue()) 1800 return N1; 1801 } 1802 1803 // If the shuffle itself creates a splat, build the vector directly. 1804 if (AllSame && SameNumElts) { 1805 EVT BuildVT = BV->getValueType(0); 1806 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1807 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1808 1809 // We may have jumped through bitcasts, so the type of the 1810 // BUILD_VECTOR may not match the type of the shuffle. 1811 if (BuildVT != VT) 1812 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1813 return NewBV; 1814 } 1815 } 1816 } 1817 1818 FoldingSetNodeID ID; 1819 SDValue Ops[2] = { N1, N2 }; 1820 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1821 for (int i = 0; i != NElts; ++i) 1822 ID.AddInteger(MaskVec[i]); 1823 1824 void* IP = nullptr; 1825 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1826 return SDValue(E, 0); 1827 1828 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1829 // SDNode doesn't have access to it. This memory will be "leaked" when 1830 // the node is deallocated, but recovered when the NodeAllocator is released. 1831 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1832 llvm::copy(MaskVec, MaskAlloc); 1833 1834 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1835 dl.getDebugLoc(), MaskAlloc); 1836 createOperands(N, Ops); 1837 1838 CSEMap.InsertNode(N, IP); 1839 InsertNode(N); 1840 SDValue V = SDValue(N, 0); 1841 NewSDValueDbgMsg(V, "Creating new node: ", this); 1842 return V; 1843 } 1844 1845 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1846 EVT VT = SV.getValueType(0); 1847 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1848 ShuffleVectorSDNode::commuteMask(MaskVec); 1849 1850 SDValue Op0 = SV.getOperand(0); 1851 SDValue Op1 = SV.getOperand(1); 1852 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1853 } 1854 1855 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1856 FoldingSetNodeID ID; 1857 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1858 ID.AddInteger(RegNo); 1859 void *IP = nullptr; 1860 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1861 return SDValue(E, 0); 1862 1863 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1864 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1865 CSEMap.InsertNode(N, IP); 1866 InsertNode(N); 1867 return SDValue(N, 0); 1868 } 1869 1870 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1871 FoldingSetNodeID ID; 1872 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1873 ID.AddPointer(RegMask); 1874 void *IP = nullptr; 1875 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1876 return SDValue(E, 0); 1877 1878 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1879 CSEMap.InsertNode(N, IP); 1880 InsertNode(N); 1881 return SDValue(N, 0); 1882 } 1883 1884 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1885 MCSymbol *Label) { 1886 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1887 } 1888 1889 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1890 SDValue Root, MCSymbol *Label) { 1891 FoldingSetNodeID ID; 1892 SDValue Ops[] = { Root }; 1893 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1894 ID.AddPointer(Label); 1895 void *IP = nullptr; 1896 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1897 return SDValue(E, 0); 1898 1899 auto *N = 1900 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 1901 createOperands(N, Ops); 1902 1903 CSEMap.InsertNode(N, IP); 1904 InsertNode(N); 1905 return SDValue(N, 0); 1906 } 1907 1908 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1909 int64_t Offset, bool isTarget, 1910 unsigned TargetFlags) { 1911 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1912 1913 FoldingSetNodeID ID; 1914 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1915 ID.AddPointer(BA); 1916 ID.AddInteger(Offset); 1917 ID.AddInteger(TargetFlags); 1918 void *IP = nullptr; 1919 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1920 return SDValue(E, 0); 1921 1922 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 1923 CSEMap.InsertNode(N, IP); 1924 InsertNode(N); 1925 return SDValue(N, 0); 1926 } 1927 1928 SDValue SelectionDAG::getSrcValue(const Value *V) { 1929 FoldingSetNodeID ID; 1930 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1931 ID.AddPointer(V); 1932 1933 void *IP = nullptr; 1934 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1935 return SDValue(E, 0); 1936 1937 auto *N = newSDNode<SrcValueSDNode>(V); 1938 CSEMap.InsertNode(N, IP); 1939 InsertNode(N); 1940 return SDValue(N, 0); 1941 } 1942 1943 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1944 FoldingSetNodeID ID; 1945 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 1946 ID.AddPointer(MD); 1947 1948 void *IP = nullptr; 1949 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1950 return SDValue(E, 0); 1951 1952 auto *N = newSDNode<MDNodeSDNode>(MD); 1953 CSEMap.InsertNode(N, IP); 1954 InsertNode(N); 1955 return SDValue(N, 0); 1956 } 1957 1958 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 1959 if (VT == V.getValueType()) 1960 return V; 1961 1962 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 1963 } 1964 1965 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 1966 unsigned SrcAS, unsigned DestAS) { 1967 SDValue Ops[] = {Ptr}; 1968 FoldingSetNodeID ID; 1969 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 1970 ID.AddInteger(SrcAS); 1971 ID.AddInteger(DestAS); 1972 1973 void *IP = nullptr; 1974 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1975 return SDValue(E, 0); 1976 1977 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 1978 VT, SrcAS, DestAS); 1979 createOperands(N, Ops); 1980 1981 CSEMap.InsertNode(N, IP); 1982 InsertNode(N); 1983 return SDValue(N, 0); 1984 } 1985 1986 SDValue SelectionDAG::getFreeze(SDValue V) { 1987 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 1988 } 1989 1990 /// getShiftAmountOperand - Return the specified value casted to 1991 /// the target's desired shift amount type. 1992 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 1993 EVT OpTy = Op.getValueType(); 1994 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 1995 if (OpTy == ShTy || OpTy.isVector()) return Op; 1996 1997 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 1998 } 1999 2000 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2001 SDLoc dl(Node); 2002 const TargetLowering &TLI = getTargetLoweringInfo(); 2003 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2004 EVT VT = Node->getValueType(0); 2005 SDValue Tmp1 = Node->getOperand(0); 2006 SDValue Tmp2 = Node->getOperand(1); 2007 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2008 2009 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2010 Tmp2, MachinePointerInfo(V)); 2011 SDValue VAList = VAListLoad; 2012 2013 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2014 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2015 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2016 2017 VAList = 2018 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2019 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2020 } 2021 2022 // Increment the pointer, VAList, to the next vaarg 2023 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2024 getConstant(getDataLayout().getTypeAllocSize( 2025 VT.getTypeForEVT(*getContext())), 2026 dl, VAList.getValueType())); 2027 // Store the incremented VAList to the legalized pointer 2028 Tmp1 = 2029 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2030 // Load the actual argument out of the pointer VAList 2031 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2032 } 2033 2034 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2035 SDLoc dl(Node); 2036 const TargetLowering &TLI = getTargetLoweringInfo(); 2037 // This defaults to loading a pointer from the input and storing it to the 2038 // output, returning the chain. 2039 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2040 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2041 SDValue Tmp1 = 2042 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2043 Node->getOperand(2), MachinePointerInfo(VS)); 2044 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2045 MachinePointerInfo(VD)); 2046 } 2047 2048 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2049 const DataLayout &DL = getDataLayout(); 2050 Type *Ty = VT.getTypeForEVT(*getContext()); 2051 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2052 2053 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2054 return RedAlign; 2055 2056 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2057 const Align StackAlign = TFI->getStackAlign(); 2058 2059 // See if we can choose a smaller ABI alignment in cases where it's an 2060 // illegal vector type that will get broken down. 2061 if (RedAlign > StackAlign) { 2062 EVT IntermediateVT; 2063 MVT RegisterVT; 2064 unsigned NumIntermediates; 2065 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2066 NumIntermediates, RegisterVT); 2067 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2068 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2069 if (RedAlign2 < RedAlign) 2070 RedAlign = RedAlign2; 2071 } 2072 2073 return RedAlign; 2074 } 2075 2076 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2077 MachineFrameInfo &MFI = MF->getFrameInfo(); 2078 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2079 int StackID = 0; 2080 if (Bytes.isScalable()) 2081 StackID = TFI->getStackIDForScalableVectors(); 2082 // The stack id gives an indication of whether the object is scalable or 2083 // not, so it's safe to pass in the minimum size here. 2084 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2085 false, nullptr, StackID); 2086 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2087 } 2088 2089 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2090 Type *Ty = VT.getTypeForEVT(*getContext()); 2091 Align StackAlign = 2092 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2093 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2094 } 2095 2096 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2097 TypeSize VT1Size = VT1.getStoreSize(); 2098 TypeSize VT2Size = VT2.getStoreSize(); 2099 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2100 "Don't know how to choose the maximum size when creating a stack " 2101 "temporary"); 2102 TypeSize Bytes = 2103 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2104 2105 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2106 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2107 const DataLayout &DL = getDataLayout(); 2108 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2109 return CreateStackTemporary(Bytes, Align); 2110 } 2111 2112 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2113 ISD::CondCode Cond, const SDLoc &dl) { 2114 EVT OpVT = N1.getValueType(); 2115 2116 // These setcc operations always fold. 2117 switch (Cond) { 2118 default: break; 2119 case ISD::SETFALSE: 2120 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2121 case ISD::SETTRUE: 2122 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2123 2124 case ISD::SETOEQ: 2125 case ISD::SETOGT: 2126 case ISD::SETOGE: 2127 case ISD::SETOLT: 2128 case ISD::SETOLE: 2129 case ISD::SETONE: 2130 case ISD::SETO: 2131 case ISD::SETUO: 2132 case ISD::SETUEQ: 2133 case ISD::SETUNE: 2134 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2135 break; 2136 } 2137 2138 if (OpVT.isInteger()) { 2139 // For EQ and NE, we can always pick a value for the undef to make the 2140 // predicate pass or fail, so we can return undef. 2141 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2142 // icmp eq/ne X, undef -> undef. 2143 if ((N1.isUndef() || N2.isUndef()) && 2144 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2145 return getUNDEF(VT); 2146 2147 // If both operands are undef, we can return undef for int comparison. 2148 // icmp undef, undef -> undef. 2149 if (N1.isUndef() && N2.isUndef()) 2150 return getUNDEF(VT); 2151 2152 // icmp X, X -> true/false 2153 // icmp X, undef -> true/false because undef could be X. 2154 if (N1 == N2) 2155 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2156 } 2157 2158 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2159 const APInt &C2 = N2C->getAPIntValue(); 2160 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2161 const APInt &C1 = N1C->getAPIntValue(); 2162 2163 switch (Cond) { 2164 default: llvm_unreachable("Unknown integer setcc!"); 2165 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2166 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2167 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2168 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2169 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2170 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2171 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2172 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2173 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2174 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2175 } 2176 } 2177 } 2178 2179 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2180 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2181 2182 if (N1CFP && N2CFP) { 2183 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2184 switch (Cond) { 2185 default: break; 2186 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2187 return getUNDEF(VT); 2188 LLVM_FALLTHROUGH; 2189 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2190 OpVT); 2191 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2192 return getUNDEF(VT); 2193 LLVM_FALLTHROUGH; 2194 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2195 R==APFloat::cmpLessThan, dl, VT, 2196 OpVT); 2197 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2198 return getUNDEF(VT); 2199 LLVM_FALLTHROUGH; 2200 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2201 OpVT); 2202 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2203 return getUNDEF(VT); 2204 LLVM_FALLTHROUGH; 2205 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2206 VT, OpVT); 2207 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2208 return getUNDEF(VT); 2209 LLVM_FALLTHROUGH; 2210 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2211 R==APFloat::cmpEqual, dl, VT, 2212 OpVT); 2213 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2214 return getUNDEF(VT); 2215 LLVM_FALLTHROUGH; 2216 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2217 R==APFloat::cmpEqual, dl, VT, OpVT); 2218 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2219 OpVT); 2220 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2221 OpVT); 2222 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2223 R==APFloat::cmpEqual, dl, VT, 2224 OpVT); 2225 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2226 OpVT); 2227 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2228 R==APFloat::cmpLessThan, dl, VT, 2229 OpVT); 2230 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2231 R==APFloat::cmpUnordered, dl, VT, 2232 OpVT); 2233 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2234 VT, OpVT); 2235 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2236 OpVT); 2237 } 2238 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2239 // Ensure that the constant occurs on the RHS. 2240 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2241 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2242 return SDValue(); 2243 return getSetCC(dl, VT, N2, N1, SwappedCond); 2244 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2245 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2246 // If an operand is known to be a nan (or undef that could be a nan), we can 2247 // fold it. 2248 // Choosing NaN for the undef will always make unordered comparison succeed 2249 // and ordered comparison fails. 2250 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2251 switch (ISD::getUnorderedFlavor(Cond)) { 2252 default: 2253 llvm_unreachable("Unknown flavor!"); 2254 case 0: // Known false. 2255 return getBoolConstant(false, dl, VT, OpVT); 2256 case 1: // Known true. 2257 return getBoolConstant(true, dl, VT, OpVT); 2258 case 2: // Undefined. 2259 return getUNDEF(VT); 2260 } 2261 } 2262 2263 // Could not fold it. 2264 return SDValue(); 2265 } 2266 2267 /// See if the specified operand can be simplified with the knowledge that only 2268 /// the bits specified by DemandedBits are used. 2269 /// TODO: really we should be making this into the DAG equivalent of 2270 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2271 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2272 EVT VT = V.getValueType(); 2273 2274 if (VT.isScalableVector()) 2275 return SDValue(); 2276 2277 APInt DemandedElts = VT.isVector() 2278 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2279 : APInt(1, 1); 2280 return GetDemandedBits(V, DemandedBits, DemandedElts); 2281 } 2282 2283 /// See if the specified operand can be simplified with the knowledge that only 2284 /// the bits specified by DemandedBits are used in the elements specified by 2285 /// DemandedElts. 2286 /// TODO: really we should be making this into the DAG equivalent of 2287 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2288 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2289 const APInt &DemandedElts) { 2290 switch (V.getOpcode()) { 2291 default: 2292 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2293 *this, 0); 2294 case ISD::Constant: { 2295 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2296 APInt NewVal = CVal & DemandedBits; 2297 if (NewVal != CVal) 2298 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2299 break; 2300 } 2301 case ISD::SRL: 2302 // Only look at single-use SRLs. 2303 if (!V.getNode()->hasOneUse()) 2304 break; 2305 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2306 // See if we can recursively simplify the LHS. 2307 unsigned Amt = RHSC->getZExtValue(); 2308 2309 // Watch out for shift count overflow though. 2310 if (Amt >= DemandedBits.getBitWidth()) 2311 break; 2312 APInt SrcDemandedBits = DemandedBits << Amt; 2313 if (SDValue SimplifyLHS = 2314 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2315 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2316 V.getOperand(1)); 2317 } 2318 break; 2319 } 2320 return SDValue(); 2321 } 2322 2323 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2324 /// use this predicate to simplify operations downstream. 2325 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2326 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2327 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2328 } 2329 2330 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2331 /// this predicate to simplify operations downstream. Mask is known to be zero 2332 /// for bits that V cannot have. 2333 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2334 unsigned Depth) const { 2335 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2336 } 2337 2338 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2339 /// DemandedElts. We use this predicate to simplify operations downstream. 2340 /// Mask is known to be zero for bits that V cannot have. 2341 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2342 const APInt &DemandedElts, 2343 unsigned Depth) const { 2344 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2345 } 2346 2347 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2348 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2349 unsigned Depth) const { 2350 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2351 } 2352 2353 /// isSplatValue - Return true if the vector V has the same value 2354 /// across all DemandedElts. For scalable vectors it does not make 2355 /// sense to specify which elements are demanded or undefined, therefore 2356 /// they are simply ignored. 2357 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2358 APInt &UndefElts, unsigned Depth) { 2359 EVT VT = V.getValueType(); 2360 assert(VT.isVector() && "Vector type expected"); 2361 2362 if (!VT.isScalableVector() && !DemandedElts) 2363 return false; // No demanded elts, better to assume we don't know anything. 2364 2365 if (Depth >= MaxRecursionDepth) 2366 return false; // Limit search depth. 2367 2368 // Deal with some common cases here that work for both fixed and scalable 2369 // vector types. 2370 switch (V.getOpcode()) { 2371 case ISD::SPLAT_VECTOR: 2372 UndefElts = V.getOperand(0).isUndef() 2373 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2374 : APInt(DemandedElts.getBitWidth(), 0); 2375 return true; 2376 case ISD::ADD: 2377 case ISD::SUB: 2378 case ISD::AND: { 2379 APInt UndefLHS, UndefRHS; 2380 SDValue LHS = V.getOperand(0); 2381 SDValue RHS = V.getOperand(1); 2382 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2383 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2384 UndefElts = UndefLHS | UndefRHS; 2385 return true; 2386 } 2387 break; 2388 } 2389 case ISD::TRUNCATE: 2390 case ISD::SIGN_EXTEND: 2391 case ISD::ZERO_EXTEND: 2392 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2393 } 2394 2395 // We don't support other cases than those above for scalable vectors at 2396 // the moment. 2397 if (VT.isScalableVector()) 2398 return false; 2399 2400 unsigned NumElts = VT.getVectorNumElements(); 2401 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2402 UndefElts = APInt::getNullValue(NumElts); 2403 2404 switch (V.getOpcode()) { 2405 case ISD::BUILD_VECTOR: { 2406 SDValue Scl; 2407 for (unsigned i = 0; i != NumElts; ++i) { 2408 SDValue Op = V.getOperand(i); 2409 if (Op.isUndef()) { 2410 UndefElts.setBit(i); 2411 continue; 2412 } 2413 if (!DemandedElts[i]) 2414 continue; 2415 if (Scl && Scl != Op) 2416 return false; 2417 Scl = Op; 2418 } 2419 return true; 2420 } 2421 case ISD::VECTOR_SHUFFLE: { 2422 // Check if this is a shuffle node doing a splat. 2423 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2424 int SplatIndex = -1; 2425 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2426 for (int i = 0; i != (int)NumElts; ++i) { 2427 int M = Mask[i]; 2428 if (M < 0) { 2429 UndefElts.setBit(i); 2430 continue; 2431 } 2432 if (!DemandedElts[i]) 2433 continue; 2434 if (0 <= SplatIndex && SplatIndex != M) 2435 return false; 2436 SplatIndex = M; 2437 } 2438 return true; 2439 } 2440 case ISD::EXTRACT_SUBVECTOR: { 2441 // Offset the demanded elts by the subvector index. 2442 SDValue Src = V.getOperand(0); 2443 uint64_t Idx = V.getConstantOperandVal(1); 2444 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2445 APInt UndefSrcElts; 2446 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2447 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2448 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2449 return true; 2450 } 2451 break; 2452 } 2453 } 2454 2455 return false; 2456 } 2457 2458 /// Helper wrapper to main isSplatValue function. 2459 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2460 EVT VT = V.getValueType(); 2461 assert(VT.isVector() && "Vector type expected"); 2462 2463 APInt UndefElts; 2464 APInt DemandedElts; 2465 2466 // For now we don't support this with scalable vectors. 2467 if (!VT.isScalableVector()) 2468 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2469 return isSplatValue(V, DemandedElts, UndefElts) && 2470 (AllowUndefs || !UndefElts); 2471 } 2472 2473 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2474 V = peekThroughExtractSubvectors(V); 2475 2476 EVT VT = V.getValueType(); 2477 unsigned Opcode = V.getOpcode(); 2478 switch (Opcode) { 2479 default: { 2480 APInt UndefElts; 2481 APInt DemandedElts; 2482 2483 if (!VT.isScalableVector()) 2484 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2485 2486 if (isSplatValue(V, DemandedElts, UndefElts)) { 2487 if (VT.isScalableVector()) { 2488 // DemandedElts and UndefElts are ignored for scalable vectors, since 2489 // the only supported cases are SPLAT_VECTOR nodes. 2490 SplatIdx = 0; 2491 } else { 2492 // Handle case where all demanded elements are UNDEF. 2493 if (DemandedElts.isSubsetOf(UndefElts)) { 2494 SplatIdx = 0; 2495 return getUNDEF(VT); 2496 } 2497 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2498 } 2499 return V; 2500 } 2501 break; 2502 } 2503 case ISD::SPLAT_VECTOR: 2504 SplatIdx = 0; 2505 return V; 2506 case ISD::VECTOR_SHUFFLE: { 2507 if (VT.isScalableVector()) 2508 return SDValue(); 2509 2510 // Check if this is a shuffle node doing a splat. 2511 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2512 // getTargetVShiftNode currently struggles without the splat source. 2513 auto *SVN = cast<ShuffleVectorSDNode>(V); 2514 if (!SVN->isSplat()) 2515 break; 2516 int Idx = SVN->getSplatIndex(); 2517 int NumElts = V.getValueType().getVectorNumElements(); 2518 SplatIdx = Idx % NumElts; 2519 return V.getOperand(Idx / NumElts); 2520 } 2521 } 2522 2523 return SDValue(); 2524 } 2525 2526 SDValue SelectionDAG::getSplatValue(SDValue V) { 2527 int SplatIdx; 2528 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) 2529 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), 2530 SrcVector.getValueType().getScalarType(), SrcVector, 2531 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2532 return SDValue(); 2533 } 2534 2535 const APInt * 2536 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2537 const APInt &DemandedElts) const { 2538 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2539 V.getOpcode() == ISD::SRA) && 2540 "Unknown shift node"); 2541 unsigned BitWidth = V.getScalarValueSizeInBits(); 2542 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2543 // Shifting more than the bitwidth is not valid. 2544 const APInt &ShAmt = SA->getAPIntValue(); 2545 if (ShAmt.ult(BitWidth)) 2546 return &ShAmt; 2547 } 2548 return nullptr; 2549 } 2550 2551 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2552 SDValue V, const APInt &DemandedElts) const { 2553 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2554 V.getOpcode() == ISD::SRA) && 2555 "Unknown shift node"); 2556 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2557 return ValidAmt; 2558 unsigned BitWidth = V.getScalarValueSizeInBits(); 2559 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2560 if (!BV) 2561 return nullptr; 2562 const APInt *MinShAmt = nullptr; 2563 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2564 if (!DemandedElts[i]) 2565 continue; 2566 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2567 if (!SA) 2568 return nullptr; 2569 // Shifting more than the bitwidth is not valid. 2570 const APInt &ShAmt = SA->getAPIntValue(); 2571 if (ShAmt.uge(BitWidth)) 2572 return nullptr; 2573 if (MinShAmt && MinShAmt->ule(ShAmt)) 2574 continue; 2575 MinShAmt = &ShAmt; 2576 } 2577 return MinShAmt; 2578 } 2579 2580 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2581 SDValue V, const APInt &DemandedElts) const { 2582 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2583 V.getOpcode() == ISD::SRA) && 2584 "Unknown shift node"); 2585 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2586 return ValidAmt; 2587 unsigned BitWidth = V.getScalarValueSizeInBits(); 2588 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2589 if (!BV) 2590 return nullptr; 2591 const APInt *MaxShAmt = nullptr; 2592 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2593 if (!DemandedElts[i]) 2594 continue; 2595 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2596 if (!SA) 2597 return nullptr; 2598 // Shifting more than the bitwidth is not valid. 2599 const APInt &ShAmt = SA->getAPIntValue(); 2600 if (ShAmt.uge(BitWidth)) 2601 return nullptr; 2602 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2603 continue; 2604 MaxShAmt = &ShAmt; 2605 } 2606 return MaxShAmt; 2607 } 2608 2609 /// Determine which bits of Op are known to be either zero or one and return 2610 /// them in Known. For vectors, the known bits are those that are shared by 2611 /// every vector element. 2612 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2613 EVT VT = Op.getValueType(); 2614 2615 // TOOD: Until we have a plan for how to represent demanded elements for 2616 // scalable vectors, we can just bail out for now. 2617 if (Op.getValueType().isScalableVector()) { 2618 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2619 return KnownBits(BitWidth); 2620 } 2621 2622 APInt DemandedElts = VT.isVector() 2623 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2624 : APInt(1, 1); 2625 return computeKnownBits(Op, DemandedElts, Depth); 2626 } 2627 2628 /// Determine which bits of Op are known to be either zero or one and return 2629 /// them in Known. The DemandedElts argument allows us to only collect the known 2630 /// bits that are shared by the requested vector elements. 2631 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2632 unsigned Depth) const { 2633 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2634 2635 KnownBits Known(BitWidth); // Don't know anything. 2636 2637 // TOOD: Until we have a plan for how to represent demanded elements for 2638 // scalable vectors, we can just bail out for now. 2639 if (Op.getValueType().isScalableVector()) 2640 return Known; 2641 2642 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2643 // We know all of the bits for a constant! 2644 return KnownBits::makeConstant(C->getAPIntValue()); 2645 } 2646 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2647 // We know all of the bits for a constant fp! 2648 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2649 } 2650 2651 if (Depth >= MaxRecursionDepth) 2652 return Known; // Limit search depth. 2653 2654 KnownBits Known2; 2655 unsigned NumElts = DemandedElts.getBitWidth(); 2656 assert((!Op.getValueType().isVector() || 2657 NumElts == Op.getValueType().getVectorNumElements()) && 2658 "Unexpected vector size"); 2659 2660 if (!DemandedElts) 2661 return Known; // No demanded elts, better to assume we don't know anything. 2662 2663 unsigned Opcode = Op.getOpcode(); 2664 switch (Opcode) { 2665 case ISD::BUILD_VECTOR: 2666 // Collect the known bits that are shared by every demanded vector element. 2667 Known.Zero.setAllBits(); Known.One.setAllBits(); 2668 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2669 if (!DemandedElts[i]) 2670 continue; 2671 2672 SDValue SrcOp = Op.getOperand(i); 2673 Known2 = computeKnownBits(SrcOp, Depth + 1); 2674 2675 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2676 if (SrcOp.getValueSizeInBits() != BitWidth) { 2677 assert(SrcOp.getValueSizeInBits() > BitWidth && 2678 "Expected BUILD_VECTOR implicit truncation"); 2679 Known2 = Known2.trunc(BitWidth); 2680 } 2681 2682 // Known bits are the values that are shared by every demanded element. 2683 Known = KnownBits::commonBits(Known, Known2); 2684 2685 // If we don't know any bits, early out. 2686 if (Known.isUnknown()) 2687 break; 2688 } 2689 break; 2690 case ISD::VECTOR_SHUFFLE: { 2691 // Collect the known bits that are shared by every vector element referenced 2692 // by the shuffle. 2693 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2694 Known.Zero.setAllBits(); Known.One.setAllBits(); 2695 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2696 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2697 for (unsigned i = 0; i != NumElts; ++i) { 2698 if (!DemandedElts[i]) 2699 continue; 2700 2701 int M = SVN->getMaskElt(i); 2702 if (M < 0) { 2703 // For UNDEF elements, we don't know anything about the common state of 2704 // the shuffle result. 2705 Known.resetAll(); 2706 DemandedLHS.clearAllBits(); 2707 DemandedRHS.clearAllBits(); 2708 break; 2709 } 2710 2711 if ((unsigned)M < NumElts) 2712 DemandedLHS.setBit((unsigned)M % NumElts); 2713 else 2714 DemandedRHS.setBit((unsigned)M % NumElts); 2715 } 2716 // Known bits are the values that are shared by every demanded element. 2717 if (!!DemandedLHS) { 2718 SDValue LHS = Op.getOperand(0); 2719 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2720 Known = KnownBits::commonBits(Known, Known2); 2721 } 2722 // If we don't know any bits, early out. 2723 if (Known.isUnknown()) 2724 break; 2725 if (!!DemandedRHS) { 2726 SDValue RHS = Op.getOperand(1); 2727 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2728 Known = KnownBits::commonBits(Known, Known2); 2729 } 2730 break; 2731 } 2732 case ISD::CONCAT_VECTORS: { 2733 // Split DemandedElts and test each of the demanded subvectors. 2734 Known.Zero.setAllBits(); Known.One.setAllBits(); 2735 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2736 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2737 unsigned NumSubVectors = Op.getNumOperands(); 2738 for (unsigned i = 0; i != NumSubVectors; ++i) { 2739 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 2740 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 2741 if (!!DemandedSub) { 2742 SDValue Sub = Op.getOperand(i); 2743 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2744 Known = KnownBits::commonBits(Known, Known2); 2745 } 2746 // If we don't know any bits, early out. 2747 if (Known.isUnknown()) 2748 break; 2749 } 2750 break; 2751 } 2752 case ISD::INSERT_SUBVECTOR: { 2753 // Demand any elements from the subvector and the remainder from the src its 2754 // inserted into. 2755 SDValue Src = Op.getOperand(0); 2756 SDValue Sub = Op.getOperand(1); 2757 uint64_t Idx = Op.getConstantOperandVal(2); 2758 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2759 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2760 APInt DemandedSrcElts = DemandedElts; 2761 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2762 2763 Known.One.setAllBits(); 2764 Known.Zero.setAllBits(); 2765 if (!!DemandedSubElts) { 2766 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2767 if (Known.isUnknown()) 2768 break; // early-out. 2769 } 2770 if (!!DemandedSrcElts) { 2771 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2772 Known = KnownBits::commonBits(Known, Known2); 2773 } 2774 break; 2775 } 2776 case ISD::EXTRACT_SUBVECTOR: { 2777 // Offset the demanded elts by the subvector index. 2778 SDValue Src = Op.getOperand(0); 2779 // Bail until we can represent demanded elements for scalable vectors. 2780 if (Src.getValueType().isScalableVector()) 2781 break; 2782 uint64_t Idx = Op.getConstantOperandVal(1); 2783 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2784 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2785 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2786 break; 2787 } 2788 case ISD::SCALAR_TO_VECTOR: { 2789 // We know about scalar_to_vector as much as we know about it source, 2790 // which becomes the first element of otherwise unknown vector. 2791 if (DemandedElts != 1) 2792 break; 2793 2794 SDValue N0 = Op.getOperand(0); 2795 Known = computeKnownBits(N0, Depth + 1); 2796 if (N0.getValueSizeInBits() != BitWidth) 2797 Known = Known.trunc(BitWidth); 2798 2799 break; 2800 } 2801 case ISD::BITCAST: { 2802 SDValue N0 = Op.getOperand(0); 2803 EVT SubVT = N0.getValueType(); 2804 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2805 2806 // Ignore bitcasts from unsupported types. 2807 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2808 break; 2809 2810 // Fast handling of 'identity' bitcasts. 2811 if (BitWidth == SubBitWidth) { 2812 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2813 break; 2814 } 2815 2816 bool IsLE = getDataLayout().isLittleEndian(); 2817 2818 // Bitcast 'small element' vector to 'large element' scalar/vector. 2819 if ((BitWidth % SubBitWidth) == 0) { 2820 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2821 2822 // Collect known bits for the (larger) output by collecting the known 2823 // bits from each set of sub elements and shift these into place. 2824 // We need to separately call computeKnownBits for each set of 2825 // sub elements as the knownbits for each is likely to be different. 2826 unsigned SubScale = BitWidth / SubBitWidth; 2827 APInt SubDemandedElts(NumElts * SubScale, 0); 2828 for (unsigned i = 0; i != NumElts; ++i) 2829 if (DemandedElts[i]) 2830 SubDemandedElts.setBit(i * SubScale); 2831 2832 for (unsigned i = 0; i != SubScale; ++i) { 2833 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2834 Depth + 1); 2835 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2836 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts); 2837 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts); 2838 } 2839 } 2840 2841 // Bitcast 'large element' scalar/vector to 'small element' vector. 2842 if ((SubBitWidth % BitWidth) == 0) { 2843 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2844 2845 // Collect known bits for the (smaller) output by collecting the known 2846 // bits from the overlapping larger input elements and extracting the 2847 // sub sections we actually care about. 2848 unsigned SubScale = SubBitWidth / BitWidth; 2849 APInt SubDemandedElts(NumElts / SubScale, 0); 2850 for (unsigned i = 0; i != NumElts; ++i) 2851 if (DemandedElts[i]) 2852 SubDemandedElts.setBit(i / SubScale); 2853 2854 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2855 2856 Known.Zero.setAllBits(); Known.One.setAllBits(); 2857 for (unsigned i = 0; i != NumElts; ++i) 2858 if (DemandedElts[i]) { 2859 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2860 unsigned Offset = (Shifts % SubScale) * BitWidth; 2861 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth); 2862 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth); 2863 // If we don't know any bits, early out. 2864 if (Known.isUnknown()) 2865 break; 2866 } 2867 } 2868 break; 2869 } 2870 case ISD::AND: 2871 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2872 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2873 2874 Known &= Known2; 2875 break; 2876 case ISD::OR: 2877 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2878 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2879 2880 Known |= Known2; 2881 break; 2882 case ISD::XOR: 2883 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2884 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2885 2886 Known ^= Known2; 2887 break; 2888 case ISD::MUL: { 2889 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2890 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2891 Known = KnownBits::computeForMul(Known, Known2); 2892 break; 2893 } 2894 case ISD::UDIV: { 2895 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2896 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2897 Known = KnownBits::udiv(Known, Known2); 2898 break; 2899 } 2900 case ISD::SELECT: 2901 case ISD::VSELECT: 2902 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2903 // If we don't know any bits, early out. 2904 if (Known.isUnknown()) 2905 break; 2906 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 2907 2908 // Only known if known in both the LHS and RHS. 2909 Known = KnownBits::commonBits(Known, Known2); 2910 break; 2911 case ISD::SELECT_CC: 2912 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 2913 // If we don't know any bits, early out. 2914 if (Known.isUnknown()) 2915 break; 2916 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2917 2918 // Only known if known in both the LHS and RHS. 2919 Known = KnownBits::commonBits(Known, Known2); 2920 break; 2921 case ISD::SMULO: 2922 case ISD::UMULO: 2923 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 2924 if (Op.getResNo() != 1) 2925 break; 2926 // The boolean result conforms to getBooleanContents. 2927 // If we know the result of a setcc has the top bits zero, use this info. 2928 // We know that we have an integer-based boolean since these operations 2929 // are only available for integer. 2930 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2931 TargetLowering::ZeroOrOneBooleanContent && 2932 BitWidth > 1) 2933 Known.Zero.setBitsFrom(1); 2934 break; 2935 case ISD::SETCC: 2936 case ISD::STRICT_FSETCC: 2937 case ISD::STRICT_FSETCCS: { 2938 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 2939 // If we know the result of a setcc has the top bits zero, use this info. 2940 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 2941 TargetLowering::ZeroOrOneBooleanContent && 2942 BitWidth > 1) 2943 Known.Zero.setBitsFrom(1); 2944 break; 2945 } 2946 case ISD::SHL: 2947 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2948 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2949 Known = KnownBits::shl(Known, Known2); 2950 2951 // Minimum shift low bits are known zero. 2952 if (const APInt *ShMinAmt = 2953 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 2954 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 2955 break; 2956 case ISD::SRL: 2957 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2958 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2959 Known = KnownBits::lshr(Known, Known2); 2960 2961 // Minimum shift high bits are known zero. 2962 if (const APInt *ShMinAmt = 2963 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 2964 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 2965 break; 2966 case ISD::SRA: 2967 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2968 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2969 Known = KnownBits::ashr(Known, Known2); 2970 // TODO: Add minimum shift high known sign bits. 2971 break; 2972 case ISD::FSHL: 2973 case ISD::FSHR: 2974 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 2975 unsigned Amt = C->getAPIntValue().urem(BitWidth); 2976 2977 // For fshl, 0-shift returns the 1st arg. 2978 // For fshr, 0-shift returns the 2nd arg. 2979 if (Amt == 0) { 2980 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 2981 DemandedElts, Depth + 1); 2982 break; 2983 } 2984 2985 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 2986 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 2987 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2988 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2989 if (Opcode == ISD::FSHL) { 2990 Known.One <<= Amt; 2991 Known.Zero <<= Amt; 2992 Known2.One.lshrInPlace(BitWidth - Amt); 2993 Known2.Zero.lshrInPlace(BitWidth - Amt); 2994 } else { 2995 Known.One <<= BitWidth - Amt; 2996 Known.Zero <<= BitWidth - Amt; 2997 Known2.One.lshrInPlace(Amt); 2998 Known2.Zero.lshrInPlace(Amt); 2999 } 3000 Known.One |= Known2.One; 3001 Known.Zero |= Known2.Zero; 3002 } 3003 break; 3004 case ISD::SIGN_EXTEND_INREG: { 3005 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3006 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3007 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3008 break; 3009 } 3010 case ISD::CTTZ: 3011 case ISD::CTTZ_ZERO_UNDEF: { 3012 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3013 // If we have a known 1, its position is our upper bound. 3014 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3015 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3016 Known.Zero.setBitsFrom(LowBits); 3017 break; 3018 } 3019 case ISD::CTLZ: 3020 case ISD::CTLZ_ZERO_UNDEF: { 3021 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3022 // If we have a known 1, its position is our upper bound. 3023 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3024 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3025 Known.Zero.setBitsFrom(LowBits); 3026 break; 3027 } 3028 case ISD::CTPOP: { 3029 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3030 // If we know some of the bits are zero, they can't be one. 3031 unsigned PossibleOnes = Known2.countMaxPopulation(); 3032 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3033 break; 3034 } 3035 case ISD::PARITY: { 3036 // Parity returns 0 everywhere but the LSB. 3037 Known.Zero.setBitsFrom(1); 3038 break; 3039 } 3040 case ISD::LOAD: { 3041 LoadSDNode *LD = cast<LoadSDNode>(Op); 3042 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3043 if (ISD::isNON_EXTLoad(LD) && Cst) { 3044 // Determine any common known bits from the loaded constant pool value. 3045 Type *CstTy = Cst->getType(); 3046 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3047 // If its a vector splat, then we can (quickly) reuse the scalar path. 3048 // NOTE: We assume all elements match and none are UNDEF. 3049 if (CstTy->isVectorTy()) { 3050 if (const Constant *Splat = Cst->getSplatValue()) { 3051 Cst = Splat; 3052 CstTy = Cst->getType(); 3053 } 3054 } 3055 // TODO - do we need to handle different bitwidths? 3056 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3057 // Iterate across all vector elements finding common known bits. 3058 Known.One.setAllBits(); 3059 Known.Zero.setAllBits(); 3060 for (unsigned i = 0; i != NumElts; ++i) { 3061 if (!DemandedElts[i]) 3062 continue; 3063 if (Constant *Elt = Cst->getAggregateElement(i)) { 3064 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3065 const APInt &Value = CInt->getValue(); 3066 Known.One &= Value; 3067 Known.Zero &= ~Value; 3068 continue; 3069 } 3070 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3071 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3072 Known.One &= Value; 3073 Known.Zero &= ~Value; 3074 continue; 3075 } 3076 } 3077 Known.One.clearAllBits(); 3078 Known.Zero.clearAllBits(); 3079 break; 3080 } 3081 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3082 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3083 const APInt &Value = CInt->getValue(); 3084 Known.One = Value; 3085 Known.Zero = ~Value; 3086 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3087 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3088 Known.One = Value; 3089 Known.Zero = ~Value; 3090 } 3091 } 3092 } 3093 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3094 // If this is a ZEXTLoad and we are looking at the loaded value. 3095 EVT VT = LD->getMemoryVT(); 3096 unsigned MemBits = VT.getScalarSizeInBits(); 3097 Known.Zero.setBitsFrom(MemBits); 3098 } else if (const MDNode *Ranges = LD->getRanges()) { 3099 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3100 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3101 } 3102 break; 3103 } 3104 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3105 EVT InVT = Op.getOperand(0).getValueType(); 3106 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3107 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3108 Known = Known.zext(BitWidth); 3109 break; 3110 } 3111 case ISD::ZERO_EXTEND: { 3112 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3113 Known = Known.zext(BitWidth); 3114 break; 3115 } 3116 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3117 EVT InVT = Op.getOperand(0).getValueType(); 3118 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3119 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3120 // If the sign bit is known to be zero or one, then sext will extend 3121 // it to the top bits, else it will just zext. 3122 Known = Known.sext(BitWidth); 3123 break; 3124 } 3125 case ISD::SIGN_EXTEND: { 3126 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3127 // If the sign bit is known to be zero or one, then sext will extend 3128 // it to the top bits, else it will just zext. 3129 Known = Known.sext(BitWidth); 3130 break; 3131 } 3132 case ISD::ANY_EXTEND_VECTOR_INREG: { 3133 EVT InVT = Op.getOperand(0).getValueType(); 3134 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3135 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3136 Known = Known.anyext(BitWidth); 3137 break; 3138 } 3139 case ISD::ANY_EXTEND: { 3140 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3141 Known = Known.anyext(BitWidth); 3142 break; 3143 } 3144 case ISD::TRUNCATE: { 3145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3146 Known = Known.trunc(BitWidth); 3147 break; 3148 } 3149 case ISD::AssertZext: { 3150 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3151 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3152 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3153 Known.Zero |= (~InMask); 3154 Known.One &= (~Known.Zero); 3155 break; 3156 } 3157 case ISD::AssertAlign: { 3158 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3159 assert(LogOfAlign != 0); 3160 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3161 // well as clearing one bits. 3162 Known.Zero.setLowBits(LogOfAlign); 3163 Known.One.clearLowBits(LogOfAlign); 3164 break; 3165 } 3166 case ISD::FGETSIGN: 3167 // All bits are zero except the low bit. 3168 Known.Zero.setBitsFrom(1); 3169 break; 3170 case ISD::USUBO: 3171 case ISD::SSUBO: 3172 if (Op.getResNo() == 1) { 3173 // If we know the result of a setcc has the top bits zero, use this info. 3174 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3175 TargetLowering::ZeroOrOneBooleanContent && 3176 BitWidth > 1) 3177 Known.Zero.setBitsFrom(1); 3178 break; 3179 } 3180 LLVM_FALLTHROUGH; 3181 case ISD::SUB: 3182 case ISD::SUBC: { 3183 assert(Op.getResNo() == 0 && 3184 "We only compute knownbits for the difference here."); 3185 3186 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3187 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3188 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3189 Known, Known2); 3190 break; 3191 } 3192 case ISD::UADDO: 3193 case ISD::SADDO: 3194 case ISD::ADDCARRY: 3195 if (Op.getResNo() == 1) { 3196 // If we know the result of a setcc has the top bits zero, use this info. 3197 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3198 TargetLowering::ZeroOrOneBooleanContent && 3199 BitWidth > 1) 3200 Known.Zero.setBitsFrom(1); 3201 break; 3202 } 3203 LLVM_FALLTHROUGH; 3204 case ISD::ADD: 3205 case ISD::ADDC: 3206 case ISD::ADDE: { 3207 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3208 3209 // With ADDE and ADDCARRY, a carry bit may be added in. 3210 KnownBits Carry(1); 3211 if (Opcode == ISD::ADDE) 3212 // Can't track carry from glue, set carry to unknown. 3213 Carry.resetAll(); 3214 else if (Opcode == ISD::ADDCARRY) 3215 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3216 // the trouble (how often will we find a known carry bit). And I haven't 3217 // tested this very much yet, but something like this might work: 3218 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3219 // Carry = Carry.zextOrTrunc(1, false); 3220 Carry.resetAll(); 3221 else 3222 Carry.setAllZero(); 3223 3224 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3225 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3226 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3227 break; 3228 } 3229 case ISD::SREM: { 3230 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3231 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3232 Known = KnownBits::srem(Known, Known2); 3233 break; 3234 } 3235 case ISD::UREM: { 3236 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3237 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3238 Known = KnownBits::urem(Known, Known2); 3239 break; 3240 } 3241 case ISD::EXTRACT_ELEMENT: { 3242 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3243 const unsigned Index = Op.getConstantOperandVal(1); 3244 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3245 3246 // Remove low part of known bits mask 3247 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3248 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3249 3250 // Remove high part of known bit mask 3251 Known = Known.trunc(EltBitWidth); 3252 break; 3253 } 3254 case ISD::EXTRACT_VECTOR_ELT: { 3255 SDValue InVec = Op.getOperand(0); 3256 SDValue EltNo = Op.getOperand(1); 3257 EVT VecVT = InVec.getValueType(); 3258 // computeKnownBits not yet implemented for scalable vectors. 3259 if (VecVT.isScalableVector()) 3260 break; 3261 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3262 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3263 3264 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3265 // anything about the extended bits. 3266 if (BitWidth > EltBitWidth) 3267 Known = Known.trunc(EltBitWidth); 3268 3269 // If we know the element index, just demand that vector element, else for 3270 // an unknown element index, ignore DemandedElts and demand them all. 3271 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3272 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3273 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3274 DemandedSrcElts = 3275 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3276 3277 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3278 if (BitWidth > EltBitWidth) 3279 Known = Known.anyext(BitWidth); 3280 break; 3281 } 3282 case ISD::INSERT_VECTOR_ELT: { 3283 // If we know the element index, split the demand between the 3284 // source vector and the inserted element, otherwise assume we need 3285 // the original demanded vector elements and the value. 3286 SDValue InVec = Op.getOperand(0); 3287 SDValue InVal = Op.getOperand(1); 3288 SDValue EltNo = Op.getOperand(2); 3289 bool DemandedVal = true; 3290 APInt DemandedVecElts = DemandedElts; 3291 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3292 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3293 unsigned EltIdx = CEltNo->getZExtValue(); 3294 DemandedVal = !!DemandedElts[EltIdx]; 3295 DemandedVecElts.clearBit(EltIdx); 3296 } 3297 Known.One.setAllBits(); 3298 Known.Zero.setAllBits(); 3299 if (DemandedVal) { 3300 Known2 = computeKnownBits(InVal, Depth + 1); 3301 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3302 } 3303 if (!!DemandedVecElts) { 3304 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3305 Known = KnownBits::commonBits(Known, Known2); 3306 } 3307 break; 3308 } 3309 case ISD::BITREVERSE: { 3310 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3311 Known = Known2.reverseBits(); 3312 break; 3313 } 3314 case ISD::BSWAP: { 3315 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3316 Known = Known2.byteSwap(); 3317 break; 3318 } 3319 case ISD::ABS: { 3320 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3321 Known = Known2.abs(); 3322 break; 3323 } 3324 case ISD::UMIN: { 3325 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3326 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3327 Known = KnownBits::umin(Known, Known2); 3328 break; 3329 } 3330 case ISD::UMAX: { 3331 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3332 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3333 Known = KnownBits::umax(Known, Known2); 3334 break; 3335 } 3336 case ISD::SMIN: 3337 case ISD::SMAX: { 3338 // If we have a clamp pattern, we know that the number of sign bits will be 3339 // the minimum of the clamp min/max range. 3340 bool IsMax = (Opcode == ISD::SMAX); 3341 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3342 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3343 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3344 CstHigh = 3345 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3346 if (CstLow && CstHigh) { 3347 if (!IsMax) 3348 std::swap(CstLow, CstHigh); 3349 3350 const APInt &ValueLow = CstLow->getAPIntValue(); 3351 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3352 if (ValueLow.sle(ValueHigh)) { 3353 unsigned LowSignBits = ValueLow.getNumSignBits(); 3354 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3355 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3356 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3357 Known.One.setHighBits(MinSignBits); 3358 break; 3359 } 3360 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3361 Known.Zero.setHighBits(MinSignBits); 3362 break; 3363 } 3364 } 3365 } 3366 3367 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3368 if (Known.isUnknown()) break; // Early-out 3369 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3370 if (IsMax) 3371 Known = KnownBits::smax(Known, Known2); 3372 else 3373 Known = KnownBits::smin(Known, Known2); 3374 break; 3375 } 3376 case ISD::FrameIndex: 3377 case ISD::TargetFrameIndex: 3378 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3379 Known, getMachineFunction()); 3380 break; 3381 3382 default: 3383 if (Opcode < ISD::BUILTIN_OP_END) 3384 break; 3385 LLVM_FALLTHROUGH; 3386 case ISD::INTRINSIC_WO_CHAIN: 3387 case ISD::INTRINSIC_W_CHAIN: 3388 case ISD::INTRINSIC_VOID: 3389 // Allow the target to implement this method for its nodes. 3390 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3391 break; 3392 } 3393 3394 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3395 return Known; 3396 } 3397 3398 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3399 SDValue N1) const { 3400 // X + 0 never overflow 3401 if (isNullConstant(N1)) 3402 return OFK_Never; 3403 3404 KnownBits N1Known = computeKnownBits(N1); 3405 if (N1Known.Zero.getBoolValue()) { 3406 KnownBits N0Known = computeKnownBits(N0); 3407 3408 bool overflow; 3409 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3410 if (!overflow) 3411 return OFK_Never; 3412 } 3413 3414 // mulhi + 1 never overflow 3415 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3416 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3417 return OFK_Never; 3418 3419 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3420 KnownBits N0Known = computeKnownBits(N0); 3421 3422 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3423 return OFK_Never; 3424 } 3425 3426 return OFK_Sometime; 3427 } 3428 3429 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3430 EVT OpVT = Val.getValueType(); 3431 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3432 3433 // Is the constant a known power of 2? 3434 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3435 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3436 3437 // A left-shift of a constant one will have exactly one bit set because 3438 // shifting the bit off the end is undefined. 3439 if (Val.getOpcode() == ISD::SHL) { 3440 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3441 if (C && C->getAPIntValue() == 1) 3442 return true; 3443 } 3444 3445 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3446 // one bit set. 3447 if (Val.getOpcode() == ISD::SRL) { 3448 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3449 if (C && C->getAPIntValue().isSignMask()) 3450 return true; 3451 } 3452 3453 // Are all operands of a build vector constant powers of two? 3454 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3455 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3457 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3458 return false; 3459 })) 3460 return true; 3461 3462 // More could be done here, though the above checks are enough 3463 // to handle some common cases. 3464 3465 // Fall back to computeKnownBits to catch other known cases. 3466 KnownBits Known = computeKnownBits(Val); 3467 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3468 } 3469 3470 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3471 EVT VT = Op.getValueType(); 3472 3473 // TODO: Assume we don't know anything for now. 3474 if (VT.isScalableVector()) 3475 return 1; 3476 3477 APInt DemandedElts = VT.isVector() 3478 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3479 : APInt(1, 1); 3480 return ComputeNumSignBits(Op, DemandedElts, Depth); 3481 } 3482 3483 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3484 unsigned Depth) const { 3485 EVT VT = Op.getValueType(); 3486 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3487 unsigned VTBits = VT.getScalarSizeInBits(); 3488 unsigned NumElts = DemandedElts.getBitWidth(); 3489 unsigned Tmp, Tmp2; 3490 unsigned FirstAnswer = 1; 3491 3492 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3493 const APInt &Val = C->getAPIntValue(); 3494 return Val.getNumSignBits(); 3495 } 3496 3497 if (Depth >= MaxRecursionDepth) 3498 return 1; // Limit search depth. 3499 3500 if (!DemandedElts || VT.isScalableVector()) 3501 return 1; // No demanded elts, better to assume we don't know anything. 3502 3503 unsigned Opcode = Op.getOpcode(); 3504 switch (Opcode) { 3505 default: break; 3506 case ISD::AssertSext: 3507 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3508 return VTBits-Tmp+1; 3509 case ISD::AssertZext: 3510 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3511 return VTBits-Tmp; 3512 3513 case ISD::BUILD_VECTOR: 3514 Tmp = VTBits; 3515 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3516 if (!DemandedElts[i]) 3517 continue; 3518 3519 SDValue SrcOp = Op.getOperand(i); 3520 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3521 3522 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3523 if (SrcOp.getValueSizeInBits() != VTBits) { 3524 assert(SrcOp.getValueSizeInBits() > VTBits && 3525 "Expected BUILD_VECTOR implicit truncation"); 3526 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3527 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3528 } 3529 Tmp = std::min(Tmp, Tmp2); 3530 } 3531 return Tmp; 3532 3533 case ISD::VECTOR_SHUFFLE: { 3534 // Collect the minimum number of sign bits that are shared by every vector 3535 // element referenced by the shuffle. 3536 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3537 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3538 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3539 for (unsigned i = 0; i != NumElts; ++i) { 3540 int M = SVN->getMaskElt(i); 3541 if (!DemandedElts[i]) 3542 continue; 3543 // For UNDEF elements, we don't know anything about the common state of 3544 // the shuffle result. 3545 if (M < 0) 3546 return 1; 3547 if ((unsigned)M < NumElts) 3548 DemandedLHS.setBit((unsigned)M % NumElts); 3549 else 3550 DemandedRHS.setBit((unsigned)M % NumElts); 3551 } 3552 Tmp = std::numeric_limits<unsigned>::max(); 3553 if (!!DemandedLHS) 3554 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3555 if (!!DemandedRHS) { 3556 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3557 Tmp = std::min(Tmp, Tmp2); 3558 } 3559 // If we don't know anything, early out and try computeKnownBits fall-back. 3560 if (Tmp == 1) 3561 break; 3562 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3563 return Tmp; 3564 } 3565 3566 case ISD::BITCAST: { 3567 SDValue N0 = Op.getOperand(0); 3568 EVT SrcVT = N0.getValueType(); 3569 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3570 3571 // Ignore bitcasts from unsupported types.. 3572 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3573 break; 3574 3575 // Fast handling of 'identity' bitcasts. 3576 if (VTBits == SrcBits) 3577 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3578 3579 bool IsLE = getDataLayout().isLittleEndian(); 3580 3581 // Bitcast 'large element' scalar/vector to 'small element' vector. 3582 if ((SrcBits % VTBits) == 0) { 3583 assert(VT.isVector() && "Expected bitcast to vector"); 3584 3585 unsigned Scale = SrcBits / VTBits; 3586 APInt SrcDemandedElts(NumElts / Scale, 0); 3587 for (unsigned i = 0; i != NumElts; ++i) 3588 if (DemandedElts[i]) 3589 SrcDemandedElts.setBit(i / Scale); 3590 3591 // Fast case - sign splat can be simply split across the small elements. 3592 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3593 if (Tmp == SrcBits) 3594 return VTBits; 3595 3596 // Slow case - determine how far the sign extends into each sub-element. 3597 Tmp2 = VTBits; 3598 for (unsigned i = 0; i != NumElts; ++i) 3599 if (DemandedElts[i]) { 3600 unsigned SubOffset = i % Scale; 3601 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3602 SubOffset = SubOffset * VTBits; 3603 if (Tmp <= SubOffset) 3604 return 1; 3605 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3606 } 3607 return Tmp2; 3608 } 3609 break; 3610 } 3611 3612 case ISD::SIGN_EXTEND: 3613 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3614 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3615 case ISD::SIGN_EXTEND_INREG: 3616 // Max of the input and what this extends. 3617 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3618 Tmp = VTBits-Tmp+1; 3619 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3620 return std::max(Tmp, Tmp2); 3621 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3622 SDValue Src = Op.getOperand(0); 3623 EVT SrcVT = Src.getValueType(); 3624 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3625 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3626 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3627 } 3628 case ISD::SRA: 3629 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3630 // SRA X, C -> adds C sign bits. 3631 if (const APInt *ShAmt = 3632 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3633 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3634 return Tmp; 3635 case ISD::SHL: 3636 if (const APInt *ShAmt = 3637 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3638 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3639 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3640 if (ShAmt->ult(Tmp)) 3641 return Tmp - ShAmt->getZExtValue(); 3642 } 3643 break; 3644 case ISD::AND: 3645 case ISD::OR: 3646 case ISD::XOR: // NOT is handled here. 3647 // Logical binary ops preserve the number of sign bits at the worst. 3648 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3649 if (Tmp != 1) { 3650 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3651 FirstAnswer = std::min(Tmp, Tmp2); 3652 // We computed what we know about the sign bits as our first 3653 // answer. Now proceed to the generic code that uses 3654 // computeKnownBits, and pick whichever answer is better. 3655 } 3656 break; 3657 3658 case ISD::SELECT: 3659 case ISD::VSELECT: 3660 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3661 if (Tmp == 1) return 1; // Early out. 3662 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3663 return std::min(Tmp, Tmp2); 3664 case ISD::SELECT_CC: 3665 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3666 if (Tmp == 1) return 1; // Early out. 3667 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3668 return std::min(Tmp, Tmp2); 3669 3670 case ISD::SMIN: 3671 case ISD::SMAX: { 3672 // If we have a clamp pattern, we know that the number of sign bits will be 3673 // the minimum of the clamp min/max range. 3674 bool IsMax = (Opcode == ISD::SMAX); 3675 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3676 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3677 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3678 CstHigh = 3679 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3680 if (CstLow && CstHigh) { 3681 if (!IsMax) 3682 std::swap(CstLow, CstHigh); 3683 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3684 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3685 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3686 return std::min(Tmp, Tmp2); 3687 } 3688 } 3689 3690 // Fallback - just get the minimum number of sign bits of the operands. 3691 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3692 if (Tmp == 1) 3693 return 1; // Early out. 3694 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3695 return std::min(Tmp, Tmp2); 3696 } 3697 case ISD::UMIN: 3698 case ISD::UMAX: 3699 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3700 if (Tmp == 1) 3701 return 1; // Early out. 3702 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3703 return std::min(Tmp, Tmp2); 3704 case ISD::SADDO: 3705 case ISD::UADDO: 3706 case ISD::SSUBO: 3707 case ISD::USUBO: 3708 case ISD::SMULO: 3709 case ISD::UMULO: 3710 if (Op.getResNo() != 1) 3711 break; 3712 // The boolean result conforms to getBooleanContents. Fall through. 3713 // If setcc returns 0/-1, all bits are sign bits. 3714 // We know that we have an integer-based boolean since these operations 3715 // are only available for integer. 3716 if (TLI->getBooleanContents(VT.isVector(), false) == 3717 TargetLowering::ZeroOrNegativeOneBooleanContent) 3718 return VTBits; 3719 break; 3720 case ISD::SETCC: 3721 case ISD::STRICT_FSETCC: 3722 case ISD::STRICT_FSETCCS: { 3723 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3724 // If setcc returns 0/-1, all bits are sign bits. 3725 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3726 TargetLowering::ZeroOrNegativeOneBooleanContent) 3727 return VTBits; 3728 break; 3729 } 3730 case ISD::ROTL: 3731 case ISD::ROTR: 3732 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3733 3734 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3735 if (Tmp == VTBits) 3736 return VTBits; 3737 3738 if (ConstantSDNode *C = 3739 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3740 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3741 3742 // Handle rotate right by N like a rotate left by 32-N. 3743 if (Opcode == ISD::ROTR) 3744 RotAmt = (VTBits - RotAmt) % VTBits; 3745 3746 // If we aren't rotating out all of the known-in sign bits, return the 3747 // number that are left. This handles rotl(sext(x), 1) for example. 3748 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3749 } 3750 break; 3751 case ISD::ADD: 3752 case ISD::ADDC: 3753 // Add can have at most one carry bit. Thus we know that the output 3754 // is, at worst, one more bit than the inputs. 3755 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3756 if (Tmp == 1) return 1; // Early out. 3757 3758 // Special case decrementing a value (ADD X, -1): 3759 if (ConstantSDNode *CRHS = 3760 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3761 if (CRHS->isAllOnesValue()) { 3762 KnownBits Known = 3763 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3764 3765 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3766 // sign bits set. 3767 if ((Known.Zero | 1).isAllOnesValue()) 3768 return VTBits; 3769 3770 // If we are subtracting one from a positive number, there is no carry 3771 // out of the result. 3772 if (Known.isNonNegative()) 3773 return Tmp; 3774 } 3775 3776 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3777 if (Tmp2 == 1) return 1; // Early out. 3778 return std::min(Tmp, Tmp2) - 1; 3779 case ISD::SUB: 3780 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3781 if (Tmp2 == 1) return 1; // Early out. 3782 3783 // Handle NEG. 3784 if (ConstantSDNode *CLHS = 3785 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3786 if (CLHS->isNullValue()) { 3787 KnownBits Known = 3788 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3789 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3790 // sign bits set. 3791 if ((Known.Zero | 1).isAllOnesValue()) 3792 return VTBits; 3793 3794 // If the input is known to be positive (the sign bit is known clear), 3795 // the output of the NEG has the same number of sign bits as the input. 3796 if (Known.isNonNegative()) 3797 return Tmp2; 3798 3799 // Otherwise, we treat this like a SUB. 3800 } 3801 3802 // Sub can have at most one carry bit. Thus we know that the output 3803 // is, at worst, one more bit than the inputs. 3804 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3805 if (Tmp == 1) return 1; // Early out. 3806 return std::min(Tmp, Tmp2) - 1; 3807 case ISD::MUL: { 3808 // The output of the Mul can be at most twice the valid bits in the inputs. 3809 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3810 if (SignBitsOp0 == 1) 3811 break; 3812 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 3813 if (SignBitsOp1 == 1) 3814 break; 3815 unsigned OutValidBits = 3816 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 3817 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 3818 } 3819 case ISD::TRUNCATE: { 3820 // Check if the sign bits of source go down as far as the truncated value. 3821 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 3822 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3823 if (NumSrcSignBits > (NumSrcBits - VTBits)) 3824 return NumSrcSignBits - (NumSrcBits - VTBits); 3825 break; 3826 } 3827 case ISD::EXTRACT_ELEMENT: { 3828 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 3829 const int BitWidth = Op.getValueSizeInBits(); 3830 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 3831 3832 // Get reverse index (starting from 1), Op1 value indexes elements from 3833 // little end. Sign starts at big end. 3834 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 3835 3836 // If the sign portion ends in our element the subtraction gives correct 3837 // result. Otherwise it gives either negative or > bitwidth result 3838 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 3839 } 3840 case ISD::INSERT_VECTOR_ELT: { 3841 // If we know the element index, split the demand between the 3842 // source vector and the inserted element, otherwise assume we need 3843 // the original demanded vector elements and the value. 3844 SDValue InVec = Op.getOperand(0); 3845 SDValue InVal = Op.getOperand(1); 3846 SDValue EltNo = Op.getOperand(2); 3847 bool DemandedVal = true; 3848 APInt DemandedVecElts = DemandedElts; 3849 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3850 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3851 unsigned EltIdx = CEltNo->getZExtValue(); 3852 DemandedVal = !!DemandedElts[EltIdx]; 3853 DemandedVecElts.clearBit(EltIdx); 3854 } 3855 Tmp = std::numeric_limits<unsigned>::max(); 3856 if (DemandedVal) { 3857 // TODO - handle implicit truncation of inserted elements. 3858 if (InVal.getScalarValueSizeInBits() != VTBits) 3859 break; 3860 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 3861 Tmp = std::min(Tmp, Tmp2); 3862 } 3863 if (!!DemandedVecElts) { 3864 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 3865 Tmp = std::min(Tmp, Tmp2); 3866 } 3867 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3868 return Tmp; 3869 } 3870 case ISD::EXTRACT_VECTOR_ELT: { 3871 SDValue InVec = Op.getOperand(0); 3872 SDValue EltNo = Op.getOperand(1); 3873 EVT VecVT = InVec.getValueType(); 3874 const unsigned BitWidth = Op.getValueSizeInBits(); 3875 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 3876 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3877 3878 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 3879 // anything about sign bits. But if the sizes match we can derive knowledge 3880 // about sign bits from the vector operand. 3881 if (BitWidth != EltBitWidth) 3882 break; 3883 3884 // If we know the element index, just demand that vector element, else for 3885 // an unknown element index, ignore DemandedElts and demand them all. 3886 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3887 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3888 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3889 DemandedSrcElts = 3890 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3891 3892 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 3893 } 3894 case ISD::EXTRACT_SUBVECTOR: { 3895 // Offset the demanded elts by the subvector index. 3896 SDValue Src = Op.getOperand(0); 3897 // Bail until we can represent demanded elements for scalable vectors. 3898 if (Src.getValueType().isScalableVector()) 3899 break; 3900 uint64_t Idx = Op.getConstantOperandVal(1); 3901 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3902 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3903 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 3904 } 3905 case ISD::CONCAT_VECTORS: { 3906 // Determine the minimum number of sign bits across all demanded 3907 // elts of the input vectors. Early out if the result is already 1. 3908 Tmp = std::numeric_limits<unsigned>::max(); 3909 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3910 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3911 unsigned NumSubVectors = Op.getNumOperands(); 3912 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 3913 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 3914 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 3915 if (!DemandedSub) 3916 continue; 3917 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 3918 Tmp = std::min(Tmp, Tmp2); 3919 } 3920 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3921 return Tmp; 3922 } 3923 case ISD::INSERT_SUBVECTOR: { 3924 // Demand any elements from the subvector and the remainder from the src its 3925 // inserted into. 3926 SDValue Src = Op.getOperand(0); 3927 SDValue Sub = Op.getOperand(1); 3928 uint64_t Idx = Op.getConstantOperandVal(2); 3929 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3930 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3931 APInt DemandedSrcElts = DemandedElts; 3932 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 3933 3934 Tmp = std::numeric_limits<unsigned>::max(); 3935 if (!!DemandedSubElts) { 3936 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 3937 if (Tmp == 1) 3938 return 1; // early-out 3939 } 3940 if (!!DemandedSrcElts) { 3941 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 3942 Tmp = std::min(Tmp, Tmp2); 3943 } 3944 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3945 return Tmp; 3946 } 3947 } 3948 3949 // If we are looking at the loaded value of the SDNode. 3950 if (Op.getResNo() == 0) { 3951 // Handle LOADX separately here. EXTLOAD case will fallthrough. 3952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 3953 unsigned ExtType = LD->getExtensionType(); 3954 switch (ExtType) { 3955 default: break; 3956 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 3957 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 3958 return VTBits - Tmp + 1; 3959 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 3960 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 3961 return VTBits - Tmp; 3962 case ISD::NON_EXTLOAD: 3963 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 3964 // We only need to handle vectors - computeKnownBits should handle 3965 // scalar cases. 3966 Type *CstTy = Cst->getType(); 3967 if (CstTy->isVectorTy() && 3968 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 3969 Tmp = VTBits; 3970 for (unsigned i = 0; i != NumElts; ++i) { 3971 if (!DemandedElts[i]) 3972 continue; 3973 if (Constant *Elt = Cst->getAggregateElement(i)) { 3974 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3975 const APInt &Value = CInt->getValue(); 3976 Tmp = std::min(Tmp, Value.getNumSignBits()); 3977 continue; 3978 } 3979 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3980 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3981 Tmp = std::min(Tmp, Value.getNumSignBits()); 3982 continue; 3983 } 3984 } 3985 // Unknown type. Conservatively assume no bits match sign bit. 3986 return 1; 3987 } 3988 return Tmp; 3989 } 3990 } 3991 break; 3992 } 3993 } 3994 } 3995 3996 // Allow the target to implement this method for its nodes. 3997 if (Opcode >= ISD::BUILTIN_OP_END || 3998 Opcode == ISD::INTRINSIC_WO_CHAIN || 3999 Opcode == ISD::INTRINSIC_W_CHAIN || 4000 Opcode == ISD::INTRINSIC_VOID) { 4001 unsigned NumBits = 4002 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4003 if (NumBits > 1) 4004 FirstAnswer = std::max(FirstAnswer, NumBits); 4005 } 4006 4007 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4008 // use this information. 4009 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4010 4011 APInt Mask; 4012 if (Known.isNonNegative()) { // sign bit is 0 4013 Mask = Known.Zero; 4014 } else if (Known.isNegative()) { // sign bit is 1; 4015 Mask = Known.One; 4016 } else { 4017 // Nothing known. 4018 return FirstAnswer; 4019 } 4020 4021 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4022 // the number of identical bits in the top of the input value. 4023 Mask <<= Mask.getBitWidth()-VTBits; 4024 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4025 } 4026 4027 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4028 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4029 !isa<ConstantSDNode>(Op.getOperand(1))) 4030 return false; 4031 4032 if (Op.getOpcode() == ISD::OR && 4033 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4034 return false; 4035 4036 return true; 4037 } 4038 4039 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4040 // If we're told that NaNs won't happen, assume they won't. 4041 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4042 return true; 4043 4044 if (Depth >= MaxRecursionDepth) 4045 return false; // Limit search depth. 4046 4047 // TODO: Handle vectors. 4048 // If the value is a constant, we can obviously see if it is a NaN or not. 4049 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4050 return !C->getValueAPF().isNaN() || 4051 (SNaN && !C->getValueAPF().isSignaling()); 4052 } 4053 4054 unsigned Opcode = Op.getOpcode(); 4055 switch (Opcode) { 4056 case ISD::FADD: 4057 case ISD::FSUB: 4058 case ISD::FMUL: 4059 case ISD::FDIV: 4060 case ISD::FREM: 4061 case ISD::FSIN: 4062 case ISD::FCOS: { 4063 if (SNaN) 4064 return true; 4065 // TODO: Need isKnownNeverInfinity 4066 return false; 4067 } 4068 case ISD::FCANONICALIZE: 4069 case ISD::FEXP: 4070 case ISD::FEXP2: 4071 case ISD::FTRUNC: 4072 case ISD::FFLOOR: 4073 case ISD::FCEIL: 4074 case ISD::FROUND: 4075 case ISD::FROUNDEVEN: 4076 case ISD::FRINT: 4077 case ISD::FNEARBYINT: { 4078 if (SNaN) 4079 return true; 4080 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4081 } 4082 case ISD::FABS: 4083 case ISD::FNEG: 4084 case ISD::FCOPYSIGN: { 4085 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4086 } 4087 case ISD::SELECT: 4088 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4089 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4090 case ISD::FP_EXTEND: 4091 case ISD::FP_ROUND: { 4092 if (SNaN) 4093 return true; 4094 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4095 } 4096 case ISD::SINT_TO_FP: 4097 case ISD::UINT_TO_FP: 4098 return true; 4099 case ISD::FMA: 4100 case ISD::FMAD: { 4101 if (SNaN) 4102 return true; 4103 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4104 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4105 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4106 } 4107 case ISD::FSQRT: // Need is known positive 4108 case ISD::FLOG: 4109 case ISD::FLOG2: 4110 case ISD::FLOG10: 4111 case ISD::FPOWI: 4112 case ISD::FPOW: { 4113 if (SNaN) 4114 return true; 4115 // TODO: Refine on operand 4116 return false; 4117 } 4118 case ISD::FMINNUM: 4119 case ISD::FMAXNUM: { 4120 // Only one needs to be known not-nan, since it will be returned if the 4121 // other ends up being one. 4122 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4123 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4124 } 4125 case ISD::FMINNUM_IEEE: 4126 case ISD::FMAXNUM_IEEE: { 4127 if (SNaN) 4128 return true; 4129 // This can return a NaN if either operand is an sNaN, or if both operands 4130 // are NaN. 4131 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4132 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4133 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4134 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4135 } 4136 case ISD::FMINIMUM: 4137 case ISD::FMAXIMUM: { 4138 // TODO: Does this quiet or return the origina NaN as-is? 4139 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4140 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4141 } 4142 case ISD::EXTRACT_VECTOR_ELT: { 4143 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4144 } 4145 default: 4146 if (Opcode >= ISD::BUILTIN_OP_END || 4147 Opcode == ISD::INTRINSIC_WO_CHAIN || 4148 Opcode == ISD::INTRINSIC_W_CHAIN || 4149 Opcode == ISD::INTRINSIC_VOID) { 4150 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4151 } 4152 4153 return false; 4154 } 4155 } 4156 4157 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4158 assert(Op.getValueType().isFloatingPoint() && 4159 "Floating point type expected"); 4160 4161 // If the value is a constant, we can obviously see if it is a zero or not. 4162 // TODO: Add BuildVector support. 4163 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4164 return !C->isZero(); 4165 return false; 4166 } 4167 4168 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4169 assert(!Op.getValueType().isFloatingPoint() && 4170 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4171 4172 // If the value is a constant, we can obviously see if it is a zero or not. 4173 if (ISD::matchUnaryPredicate( 4174 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4175 return true; 4176 4177 // TODO: Recognize more cases here. 4178 switch (Op.getOpcode()) { 4179 default: break; 4180 case ISD::OR: 4181 if (isKnownNeverZero(Op.getOperand(1)) || 4182 isKnownNeverZero(Op.getOperand(0))) 4183 return true; 4184 break; 4185 } 4186 4187 return false; 4188 } 4189 4190 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4191 // Check the obvious case. 4192 if (A == B) return true; 4193 4194 // For for negative and positive zero. 4195 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4196 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4197 if (CA->isZero() && CB->isZero()) return true; 4198 4199 // Otherwise they may not be equal. 4200 return false; 4201 } 4202 4203 // FIXME: unify with llvm::haveNoCommonBitsSet. 4204 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4205 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4206 assert(A.getValueType() == B.getValueType() && 4207 "Values must have the same type"); 4208 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue(); 4209 } 4210 4211 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4212 ArrayRef<SDValue> Ops, 4213 SelectionDAG &DAG) { 4214 int NumOps = Ops.size(); 4215 assert(NumOps != 0 && "Can't build an empty vector!"); 4216 assert(!VT.isScalableVector() && 4217 "BUILD_VECTOR cannot be used with scalable types"); 4218 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4219 "Incorrect element count in BUILD_VECTOR!"); 4220 4221 // BUILD_VECTOR of UNDEFs is UNDEF. 4222 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4223 return DAG.getUNDEF(VT); 4224 4225 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4226 SDValue IdentitySrc; 4227 bool IsIdentity = true; 4228 for (int i = 0; i != NumOps; ++i) { 4229 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4230 Ops[i].getOperand(0).getValueType() != VT || 4231 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4232 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4233 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4234 IsIdentity = false; 4235 break; 4236 } 4237 IdentitySrc = Ops[i].getOperand(0); 4238 } 4239 if (IsIdentity) 4240 return IdentitySrc; 4241 4242 return SDValue(); 4243 } 4244 4245 /// Try to simplify vector concatenation to an input value, undef, or build 4246 /// vector. 4247 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4248 ArrayRef<SDValue> Ops, 4249 SelectionDAG &DAG) { 4250 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4251 assert(llvm::all_of(Ops, 4252 [Ops](SDValue Op) { 4253 return Ops[0].getValueType() == Op.getValueType(); 4254 }) && 4255 "Concatenation of vectors with inconsistent value types!"); 4256 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4257 VT.getVectorElementCount() && 4258 "Incorrect element count in vector concatenation!"); 4259 4260 if (Ops.size() == 1) 4261 return Ops[0]; 4262 4263 // Concat of UNDEFs is UNDEF. 4264 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4265 return DAG.getUNDEF(VT); 4266 4267 // Scan the operands and look for extract operations from a single source 4268 // that correspond to insertion at the same location via this concatenation: 4269 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4270 SDValue IdentitySrc; 4271 bool IsIdentity = true; 4272 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4273 SDValue Op = Ops[i]; 4274 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4275 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4276 Op.getOperand(0).getValueType() != VT || 4277 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4278 Op.getConstantOperandVal(1) != IdentityIndex) { 4279 IsIdentity = false; 4280 break; 4281 } 4282 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4283 "Unexpected identity source vector for concat of extracts"); 4284 IdentitySrc = Op.getOperand(0); 4285 } 4286 if (IsIdentity) { 4287 assert(IdentitySrc && "Failed to set source vector of extracts"); 4288 return IdentitySrc; 4289 } 4290 4291 // The code below this point is only designed to work for fixed width 4292 // vectors, so we bail out for now. 4293 if (VT.isScalableVector()) 4294 return SDValue(); 4295 4296 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4297 // simplified to one big BUILD_VECTOR. 4298 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4299 EVT SVT = VT.getScalarType(); 4300 SmallVector<SDValue, 16> Elts; 4301 for (SDValue Op : Ops) { 4302 EVT OpVT = Op.getValueType(); 4303 if (Op.isUndef()) 4304 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4305 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4306 Elts.append(Op->op_begin(), Op->op_end()); 4307 else 4308 return SDValue(); 4309 } 4310 4311 // BUILD_VECTOR requires all inputs to be of the same type, find the 4312 // maximum type and extend them all. 4313 for (SDValue Op : Elts) 4314 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4315 4316 if (SVT.bitsGT(VT.getScalarType())) { 4317 for (SDValue &Op : Elts) { 4318 if (Op.isUndef()) 4319 Op = DAG.getUNDEF(SVT); 4320 else 4321 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4322 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4323 : DAG.getSExtOrTrunc(Op, DL, SVT); 4324 } 4325 } 4326 4327 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4328 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4329 return V; 4330 } 4331 4332 /// Gets or creates the specified node. 4333 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4334 FoldingSetNodeID ID; 4335 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4336 void *IP = nullptr; 4337 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4338 return SDValue(E, 0); 4339 4340 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4341 getVTList(VT)); 4342 CSEMap.InsertNode(N, IP); 4343 4344 InsertNode(N); 4345 SDValue V = SDValue(N, 0); 4346 NewSDValueDbgMsg(V, "Creating new node: ", this); 4347 return V; 4348 } 4349 4350 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4351 SDValue Operand) { 4352 SDNodeFlags Flags; 4353 if (Inserter) 4354 Flags = Inserter->getFlags(); 4355 return getNode(Opcode, DL, VT, Operand, Flags); 4356 } 4357 4358 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4359 SDValue Operand, const SDNodeFlags Flags) { 4360 // Constant fold unary operations with an integer constant operand. Even 4361 // opaque constant will be folded, because the folding of unary operations 4362 // doesn't create new constants with different values. Nevertheless, the 4363 // opaque flag is preserved during folding to prevent future folding with 4364 // other constants. 4365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4366 const APInt &Val = C->getAPIntValue(); 4367 switch (Opcode) { 4368 default: break; 4369 case ISD::SIGN_EXTEND: 4370 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4371 C->isTargetOpcode(), C->isOpaque()); 4372 case ISD::TRUNCATE: 4373 if (C->isOpaque()) 4374 break; 4375 LLVM_FALLTHROUGH; 4376 case ISD::ANY_EXTEND: 4377 case ISD::ZERO_EXTEND: 4378 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4379 C->isTargetOpcode(), C->isOpaque()); 4380 case ISD::UINT_TO_FP: 4381 case ISD::SINT_TO_FP: { 4382 APFloat apf(EVTToAPFloatSemantics(VT), 4383 APInt::getNullValue(VT.getSizeInBits())); 4384 (void)apf.convertFromAPInt(Val, 4385 Opcode==ISD::SINT_TO_FP, 4386 APFloat::rmNearestTiesToEven); 4387 return getConstantFP(apf, DL, VT); 4388 } 4389 case ISD::BITCAST: 4390 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4391 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4392 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4393 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4394 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4395 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4396 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4397 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4398 break; 4399 case ISD::ABS: 4400 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4401 C->isOpaque()); 4402 case ISD::BITREVERSE: 4403 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4404 C->isOpaque()); 4405 case ISD::BSWAP: 4406 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4407 C->isOpaque()); 4408 case ISD::CTPOP: 4409 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4410 C->isOpaque()); 4411 case ISD::CTLZ: 4412 case ISD::CTLZ_ZERO_UNDEF: 4413 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4414 C->isOpaque()); 4415 case ISD::CTTZ: 4416 case ISD::CTTZ_ZERO_UNDEF: 4417 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4418 C->isOpaque()); 4419 case ISD::FP16_TO_FP: { 4420 bool Ignored; 4421 APFloat FPV(APFloat::IEEEhalf(), 4422 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4423 4424 // This can return overflow, underflow, or inexact; we don't care. 4425 // FIXME need to be more flexible about rounding mode. 4426 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4427 APFloat::rmNearestTiesToEven, &Ignored); 4428 return getConstantFP(FPV, DL, VT); 4429 } 4430 } 4431 } 4432 4433 // Constant fold unary operations with a floating point constant operand. 4434 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4435 APFloat V = C->getValueAPF(); // make copy 4436 switch (Opcode) { 4437 case ISD::FNEG: 4438 V.changeSign(); 4439 return getConstantFP(V, DL, VT); 4440 case ISD::FABS: 4441 V.clearSign(); 4442 return getConstantFP(V, DL, VT); 4443 case ISD::FCEIL: { 4444 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4445 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4446 return getConstantFP(V, DL, VT); 4447 break; 4448 } 4449 case ISD::FTRUNC: { 4450 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4451 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4452 return getConstantFP(V, DL, VT); 4453 break; 4454 } 4455 case ISD::FFLOOR: { 4456 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4457 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4458 return getConstantFP(V, DL, VT); 4459 break; 4460 } 4461 case ISD::FP_EXTEND: { 4462 bool ignored; 4463 // This can return overflow, underflow, or inexact; we don't care. 4464 // FIXME need to be more flexible about rounding mode. 4465 (void)V.convert(EVTToAPFloatSemantics(VT), 4466 APFloat::rmNearestTiesToEven, &ignored); 4467 return getConstantFP(V, DL, VT); 4468 } 4469 case ISD::FP_TO_SINT: 4470 case ISD::FP_TO_UINT: { 4471 bool ignored; 4472 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4473 // FIXME need to be more flexible about rounding mode. 4474 APFloat::opStatus s = 4475 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4476 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4477 break; 4478 return getConstant(IntVal, DL, VT); 4479 } 4480 case ISD::BITCAST: 4481 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4482 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4483 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4484 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4485 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4486 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4487 break; 4488 case ISD::FP_TO_FP16: { 4489 bool Ignored; 4490 // This can return overflow, underflow, or inexact; we don't care. 4491 // FIXME need to be more flexible about rounding mode. 4492 (void)V.convert(APFloat::IEEEhalf(), 4493 APFloat::rmNearestTiesToEven, &Ignored); 4494 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4495 } 4496 } 4497 } 4498 4499 // Constant fold unary operations with a vector integer or float operand. 4500 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 4501 if (BV->isConstant()) { 4502 switch (Opcode) { 4503 default: 4504 // FIXME: Entirely reasonable to perform folding of other unary 4505 // operations here as the need arises. 4506 break; 4507 case ISD::FNEG: 4508 case ISD::FABS: 4509 case ISD::FCEIL: 4510 case ISD::FTRUNC: 4511 case ISD::FFLOOR: 4512 case ISD::FP_EXTEND: 4513 case ISD::FP_TO_SINT: 4514 case ISD::FP_TO_UINT: 4515 case ISD::TRUNCATE: 4516 case ISD::ANY_EXTEND: 4517 case ISD::ZERO_EXTEND: 4518 case ISD::SIGN_EXTEND: 4519 case ISD::UINT_TO_FP: 4520 case ISD::SINT_TO_FP: 4521 case ISD::ABS: 4522 case ISD::BITREVERSE: 4523 case ISD::BSWAP: 4524 case ISD::CTLZ: 4525 case ISD::CTLZ_ZERO_UNDEF: 4526 case ISD::CTTZ: 4527 case ISD::CTTZ_ZERO_UNDEF: 4528 case ISD::CTPOP: { 4529 SDValue Ops = { Operand }; 4530 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4531 return Fold; 4532 } 4533 } 4534 } 4535 } 4536 4537 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4538 switch (Opcode) { 4539 case ISD::FREEZE: 4540 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4541 break; 4542 case ISD::TokenFactor: 4543 case ISD::MERGE_VALUES: 4544 case ISD::CONCAT_VECTORS: 4545 return Operand; // Factor, merge or concat of one node? No need. 4546 case ISD::BUILD_VECTOR: { 4547 // Attempt to simplify BUILD_VECTOR. 4548 SDValue Ops[] = {Operand}; 4549 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4550 return V; 4551 break; 4552 } 4553 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4554 case ISD::FP_EXTEND: 4555 assert(VT.isFloatingPoint() && 4556 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4557 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4558 assert((!VT.isVector() || 4559 VT.getVectorElementCount() == 4560 Operand.getValueType().getVectorElementCount()) && 4561 "Vector element count mismatch!"); 4562 assert(Operand.getValueType().bitsLT(VT) && 4563 "Invalid fpext node, dst < src!"); 4564 if (Operand.isUndef()) 4565 return getUNDEF(VT); 4566 break; 4567 case ISD::FP_TO_SINT: 4568 case ISD::FP_TO_UINT: 4569 if (Operand.isUndef()) 4570 return getUNDEF(VT); 4571 break; 4572 case ISD::SINT_TO_FP: 4573 case ISD::UINT_TO_FP: 4574 // [us]itofp(undef) = 0, because the result value is bounded. 4575 if (Operand.isUndef()) 4576 return getConstantFP(0.0, DL, VT); 4577 break; 4578 case ISD::SIGN_EXTEND: 4579 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4580 "Invalid SIGN_EXTEND!"); 4581 assert(VT.isVector() == Operand.getValueType().isVector() && 4582 "SIGN_EXTEND result type type should be vector iff the operand " 4583 "type is vector!"); 4584 if (Operand.getValueType() == VT) return Operand; // noop extension 4585 assert((!VT.isVector() || 4586 VT.getVectorElementCount() == 4587 Operand.getValueType().getVectorElementCount()) && 4588 "Vector element count mismatch!"); 4589 assert(Operand.getValueType().bitsLT(VT) && 4590 "Invalid sext node, dst < src!"); 4591 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4592 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4593 else if (OpOpcode == ISD::UNDEF) 4594 // sext(undef) = 0, because the top bits will all be the same. 4595 return getConstant(0, DL, VT); 4596 break; 4597 case ISD::ZERO_EXTEND: 4598 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4599 "Invalid ZERO_EXTEND!"); 4600 assert(VT.isVector() == Operand.getValueType().isVector() && 4601 "ZERO_EXTEND result type type should be vector iff the operand " 4602 "type is vector!"); 4603 if (Operand.getValueType() == VT) return Operand; // noop extension 4604 assert((!VT.isVector() || 4605 VT.getVectorElementCount() == 4606 Operand.getValueType().getVectorElementCount()) && 4607 "Vector element count mismatch!"); 4608 assert(Operand.getValueType().bitsLT(VT) && 4609 "Invalid zext node, dst < src!"); 4610 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4611 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4612 else if (OpOpcode == ISD::UNDEF) 4613 // zext(undef) = 0, because the top bits will be zero. 4614 return getConstant(0, DL, VT); 4615 break; 4616 case ISD::ANY_EXTEND: 4617 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4618 "Invalid ANY_EXTEND!"); 4619 assert(VT.isVector() == Operand.getValueType().isVector() && 4620 "ANY_EXTEND result type type should be vector iff the operand " 4621 "type is vector!"); 4622 if (Operand.getValueType() == VT) return Operand; // noop extension 4623 assert((!VT.isVector() || 4624 VT.getVectorElementCount() == 4625 Operand.getValueType().getVectorElementCount()) && 4626 "Vector element count mismatch!"); 4627 assert(Operand.getValueType().bitsLT(VT) && 4628 "Invalid anyext node, dst < src!"); 4629 4630 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4631 OpOpcode == ISD::ANY_EXTEND) 4632 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4633 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4634 else if (OpOpcode == ISD::UNDEF) 4635 return getUNDEF(VT); 4636 4637 // (ext (trunc x)) -> x 4638 if (OpOpcode == ISD::TRUNCATE) { 4639 SDValue OpOp = Operand.getOperand(0); 4640 if (OpOp.getValueType() == VT) { 4641 transferDbgValues(Operand, OpOp); 4642 return OpOp; 4643 } 4644 } 4645 break; 4646 case ISD::TRUNCATE: 4647 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4648 "Invalid TRUNCATE!"); 4649 assert(VT.isVector() == Operand.getValueType().isVector() && 4650 "TRUNCATE result type type should be vector iff the operand " 4651 "type is vector!"); 4652 if (Operand.getValueType() == VT) return Operand; // noop truncate 4653 assert((!VT.isVector() || 4654 VT.getVectorElementCount() == 4655 Operand.getValueType().getVectorElementCount()) && 4656 "Vector element count mismatch!"); 4657 assert(Operand.getValueType().bitsGT(VT) && 4658 "Invalid truncate node, src < dst!"); 4659 if (OpOpcode == ISD::TRUNCATE) 4660 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4661 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4662 OpOpcode == ISD::ANY_EXTEND) { 4663 // If the source is smaller than the dest, we still need an extend. 4664 if (Operand.getOperand(0).getValueType().getScalarType() 4665 .bitsLT(VT.getScalarType())) 4666 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4667 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4668 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4669 return Operand.getOperand(0); 4670 } 4671 if (OpOpcode == ISD::UNDEF) 4672 return getUNDEF(VT); 4673 break; 4674 case ISD::ANY_EXTEND_VECTOR_INREG: 4675 case ISD::ZERO_EXTEND_VECTOR_INREG: 4676 case ISD::SIGN_EXTEND_VECTOR_INREG: 4677 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4678 assert(Operand.getValueType().bitsLE(VT) && 4679 "The input must be the same size or smaller than the result."); 4680 assert(VT.getVectorNumElements() < 4681 Operand.getValueType().getVectorNumElements() && 4682 "The destination vector type must have fewer lanes than the input."); 4683 break; 4684 case ISD::ABS: 4685 assert(VT.isInteger() && VT == Operand.getValueType() && 4686 "Invalid ABS!"); 4687 if (OpOpcode == ISD::UNDEF) 4688 return getUNDEF(VT); 4689 break; 4690 case ISD::BSWAP: 4691 assert(VT.isInteger() && VT == Operand.getValueType() && 4692 "Invalid BSWAP!"); 4693 assert((VT.getScalarSizeInBits() % 16 == 0) && 4694 "BSWAP types must be a multiple of 16 bits!"); 4695 if (OpOpcode == ISD::UNDEF) 4696 return getUNDEF(VT); 4697 break; 4698 case ISD::BITREVERSE: 4699 assert(VT.isInteger() && VT == Operand.getValueType() && 4700 "Invalid BITREVERSE!"); 4701 if (OpOpcode == ISD::UNDEF) 4702 return getUNDEF(VT); 4703 break; 4704 case ISD::BITCAST: 4705 // Basic sanity checking. 4706 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4707 "Cannot BITCAST between types of different sizes!"); 4708 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4709 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4710 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4711 if (OpOpcode == ISD::UNDEF) 4712 return getUNDEF(VT); 4713 break; 4714 case ISD::SCALAR_TO_VECTOR: 4715 assert(VT.isVector() && !Operand.getValueType().isVector() && 4716 (VT.getVectorElementType() == Operand.getValueType() || 4717 (VT.getVectorElementType().isInteger() && 4718 Operand.getValueType().isInteger() && 4719 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4720 "Illegal SCALAR_TO_VECTOR node!"); 4721 if (OpOpcode == ISD::UNDEF) 4722 return getUNDEF(VT); 4723 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4724 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4725 isa<ConstantSDNode>(Operand.getOperand(1)) && 4726 Operand.getConstantOperandVal(1) == 0 && 4727 Operand.getOperand(0).getValueType() == VT) 4728 return Operand.getOperand(0); 4729 break; 4730 case ISD::FNEG: 4731 // Negation of an unknown bag of bits is still completely undefined. 4732 if (OpOpcode == ISD::UNDEF) 4733 return getUNDEF(VT); 4734 4735 if (OpOpcode == ISD::FNEG) // --X -> X 4736 return Operand.getOperand(0); 4737 break; 4738 case ISD::FABS: 4739 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4740 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4741 break; 4742 case ISD::VSCALE: 4743 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4744 break; 4745 case ISD::VECREDUCE_SMIN: 4746 case ISD::VECREDUCE_UMAX: 4747 if (Operand.getValueType().getScalarType() == MVT::i1) 4748 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 4749 break; 4750 case ISD::VECREDUCE_SMAX: 4751 case ISD::VECREDUCE_UMIN: 4752 if (Operand.getValueType().getScalarType() == MVT::i1) 4753 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 4754 break; 4755 } 4756 4757 SDNode *N; 4758 SDVTList VTs = getVTList(VT); 4759 SDValue Ops[] = {Operand}; 4760 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 4761 FoldingSetNodeID ID; 4762 AddNodeIDNode(ID, Opcode, VTs, Ops); 4763 void *IP = nullptr; 4764 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 4765 E->intersectFlagsWith(Flags); 4766 return SDValue(E, 0); 4767 } 4768 4769 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4770 N->setFlags(Flags); 4771 createOperands(N, Ops); 4772 CSEMap.InsertNode(N, IP); 4773 } else { 4774 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4775 createOperands(N, Ops); 4776 } 4777 4778 InsertNode(N); 4779 SDValue V = SDValue(N, 0); 4780 NewSDValueDbgMsg(V, "Creating new node: ", this); 4781 return V; 4782 } 4783 4784 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 4785 const APInt &C2) { 4786 switch (Opcode) { 4787 case ISD::ADD: return C1 + C2; 4788 case ISD::SUB: return C1 - C2; 4789 case ISD::MUL: return C1 * C2; 4790 case ISD::AND: return C1 & C2; 4791 case ISD::OR: return C1 | C2; 4792 case ISD::XOR: return C1 ^ C2; 4793 case ISD::SHL: return C1 << C2; 4794 case ISD::SRL: return C1.lshr(C2); 4795 case ISD::SRA: return C1.ashr(C2); 4796 case ISD::ROTL: return C1.rotl(C2); 4797 case ISD::ROTR: return C1.rotr(C2); 4798 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 4799 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 4800 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 4801 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 4802 case ISD::SADDSAT: return C1.sadd_sat(C2); 4803 case ISD::UADDSAT: return C1.uadd_sat(C2); 4804 case ISD::SSUBSAT: return C1.ssub_sat(C2); 4805 case ISD::USUBSAT: return C1.usub_sat(C2); 4806 case ISD::UDIV: 4807 if (!C2.getBoolValue()) 4808 break; 4809 return C1.udiv(C2); 4810 case ISD::UREM: 4811 if (!C2.getBoolValue()) 4812 break; 4813 return C1.urem(C2); 4814 case ISD::SDIV: 4815 if (!C2.getBoolValue()) 4816 break; 4817 return C1.sdiv(C2); 4818 case ISD::SREM: 4819 if (!C2.getBoolValue()) 4820 break; 4821 return C1.srem(C2); 4822 } 4823 return llvm::None; 4824 } 4825 4826 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 4827 const GlobalAddressSDNode *GA, 4828 const SDNode *N2) { 4829 if (GA->getOpcode() != ISD::GlobalAddress) 4830 return SDValue(); 4831 if (!TLI->isOffsetFoldingLegal(GA)) 4832 return SDValue(); 4833 auto *C2 = dyn_cast<ConstantSDNode>(N2); 4834 if (!C2) 4835 return SDValue(); 4836 int64_t Offset = C2->getSExtValue(); 4837 switch (Opcode) { 4838 case ISD::ADD: break; 4839 case ISD::SUB: Offset = -uint64_t(Offset); break; 4840 default: return SDValue(); 4841 } 4842 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 4843 GA->getOffset() + uint64_t(Offset)); 4844 } 4845 4846 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 4847 switch (Opcode) { 4848 case ISD::SDIV: 4849 case ISD::UDIV: 4850 case ISD::SREM: 4851 case ISD::UREM: { 4852 // If a divisor is zero/undef or any element of a divisor vector is 4853 // zero/undef, the whole op is undef. 4854 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 4855 SDValue Divisor = Ops[1]; 4856 if (Divisor.isUndef() || isNullConstant(Divisor)) 4857 return true; 4858 4859 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 4860 llvm::any_of(Divisor->op_values(), 4861 [](SDValue V) { return V.isUndef() || 4862 isNullConstant(V); }); 4863 // TODO: Handle signed overflow. 4864 } 4865 // TODO: Handle oversized shifts. 4866 default: 4867 return false; 4868 } 4869 } 4870 4871 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 4872 EVT VT, ArrayRef<SDValue> Ops) { 4873 // If the opcode is a target-specific ISD node, there's nothing we can 4874 // do here and the operand rules may not line up with the below, so 4875 // bail early. 4876 if (Opcode >= ISD::BUILTIN_OP_END) 4877 return SDValue(); 4878 4879 // For now, the array Ops should only contain two values. 4880 // This enforcement will be removed once this function is merged with 4881 // FoldConstantVectorArithmetic 4882 if (Ops.size() != 2) 4883 return SDValue(); 4884 4885 if (isUndef(Opcode, Ops)) 4886 return getUNDEF(VT); 4887 4888 SDNode *N1 = Ops[0].getNode(); 4889 SDNode *N2 = Ops[1].getNode(); 4890 4891 // Handle the case of two scalars. 4892 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 4893 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 4894 if (C1->isOpaque() || C2->isOpaque()) 4895 return SDValue(); 4896 4897 Optional<APInt> FoldAttempt = 4898 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 4899 if (!FoldAttempt) 4900 return SDValue(); 4901 4902 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 4903 assert((!Folded || !VT.isVector()) && 4904 "Can't fold vectors ops with scalar operands"); 4905 return Folded; 4906 } 4907 } 4908 4909 // fold (add Sym, c) -> Sym+c 4910 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 4911 return FoldSymbolOffset(Opcode, VT, GA, N2); 4912 if (TLI->isCommutativeBinOp(Opcode)) 4913 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 4914 return FoldSymbolOffset(Opcode, VT, GA, N1); 4915 4916 // TODO: All the folds below are performed lane-by-lane and assume a fixed 4917 // vector width, however we should be able to do constant folds involving 4918 // splat vector nodes too. 4919 if (VT.isScalableVector()) 4920 return SDValue(); 4921 4922 // For fixed width vectors, extract each constant element and fold them 4923 // individually. Either input may be an undef value. 4924 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 4925 if (!BV1 && !N1->isUndef()) 4926 return SDValue(); 4927 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 4928 if (!BV2 && !N2->isUndef()) 4929 return SDValue(); 4930 // If both operands are undef, that's handled the same way as scalars. 4931 if (!BV1 && !BV2) 4932 return SDValue(); 4933 4934 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) && 4935 "Vector binop with different number of elements in operands?"); 4936 4937 EVT SVT = VT.getScalarType(); 4938 EVT LegalSVT = SVT; 4939 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 4940 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 4941 if (LegalSVT.bitsLT(SVT)) 4942 return SDValue(); 4943 } 4944 SmallVector<SDValue, 4> Outputs; 4945 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands(); 4946 for (unsigned I = 0; I != NumOps; ++I) { 4947 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT); 4948 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT); 4949 if (SVT.isInteger()) { 4950 if (V1->getValueType(0).bitsGT(SVT)) 4951 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 4952 if (V2->getValueType(0).bitsGT(SVT)) 4953 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 4954 } 4955 4956 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 4957 return SDValue(); 4958 4959 // Fold one vector element. 4960 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 4961 if (LegalSVT != SVT) 4962 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 4963 4964 // Scalar folding only succeeded if the result is a constant or UNDEF. 4965 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 4966 ScalarResult.getOpcode() != ISD::ConstantFP) 4967 return SDValue(); 4968 Outputs.push_back(ScalarResult); 4969 } 4970 4971 assert(VT.getVectorNumElements() == Outputs.size() && 4972 "Vector size mismatch!"); 4973 4974 // We may have a vector type but a scalar result. Create a splat. 4975 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 4976 4977 // Build a big vector out of the scalar elements we generated. 4978 return getBuildVector(VT, SDLoc(), Outputs); 4979 } 4980 4981 // TODO: Merge with FoldConstantArithmetic 4982 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 4983 const SDLoc &DL, EVT VT, 4984 ArrayRef<SDValue> Ops, 4985 const SDNodeFlags Flags) { 4986 // If the opcode is a target-specific ISD node, there's nothing we can 4987 // do here and the operand rules may not line up with the below, so 4988 // bail early. 4989 if (Opcode >= ISD::BUILTIN_OP_END) 4990 return SDValue(); 4991 4992 if (isUndef(Opcode, Ops)) 4993 return getUNDEF(VT); 4994 4995 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 4996 if (!VT.isVector()) 4997 return SDValue(); 4998 4999 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5000 // vector width, however we should be able to do constant folds involving 5001 // splat vector nodes too. 5002 if (VT.isScalableVector()) 5003 return SDValue(); 5004 5005 // From this point onwards all vectors are assumed to be fixed width. 5006 unsigned NumElts = VT.getVectorNumElements(); 5007 5008 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5009 return !Op.getValueType().isVector() || 5010 Op.getValueType().getVectorNumElements() == NumElts; 5011 }; 5012 5013 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5014 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5015 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5016 (BV && BV->isConstant()); 5017 }; 5018 5019 // All operands must be vector types with the same number of elements as 5020 // the result type and must be either UNDEF or a build vector of constant 5021 // or UNDEF scalars. 5022 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5023 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5024 return SDValue(); 5025 5026 // If we are comparing vectors, then the result needs to be a i1 boolean 5027 // that is then sign-extended back to the legal result type. 5028 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5029 5030 // Find legal integer scalar type for constant promotion and 5031 // ensure that its scalar size is at least as large as source. 5032 EVT LegalSVT = VT.getScalarType(); 5033 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5034 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5035 if (LegalSVT.bitsLT(VT.getScalarType())) 5036 return SDValue(); 5037 } 5038 5039 // Constant fold each scalar lane separately. 5040 SmallVector<SDValue, 4> ScalarResults; 5041 for (unsigned i = 0; i != NumElts; i++) { 5042 SmallVector<SDValue, 4> ScalarOps; 5043 for (SDValue Op : Ops) { 5044 EVT InSVT = Op.getValueType().getScalarType(); 5045 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5046 if (!InBV) { 5047 // We've checked that this is UNDEF or a constant of some kind. 5048 if (Op.isUndef()) 5049 ScalarOps.push_back(getUNDEF(InSVT)); 5050 else 5051 ScalarOps.push_back(Op); 5052 continue; 5053 } 5054 5055 SDValue ScalarOp = InBV->getOperand(i); 5056 EVT ScalarVT = ScalarOp.getValueType(); 5057 5058 // Build vector (integer) scalar operands may need implicit 5059 // truncation - do this before constant folding. 5060 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5061 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5062 5063 ScalarOps.push_back(ScalarOp); 5064 } 5065 5066 // Constant fold the scalar operands. 5067 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5068 5069 // Legalize the (integer) scalar constant if necessary. 5070 if (LegalSVT != SVT) 5071 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5072 5073 // Scalar folding only succeeded if the result is a constant or UNDEF. 5074 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5075 ScalarResult.getOpcode() != ISD::ConstantFP) 5076 return SDValue(); 5077 ScalarResults.push_back(ScalarResult); 5078 } 5079 5080 SDValue V = getBuildVector(VT, DL, ScalarResults); 5081 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5082 return V; 5083 } 5084 5085 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5086 EVT VT, SDValue N1, SDValue N2) { 5087 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5088 // should. That will require dealing with a potentially non-default 5089 // rounding mode, checking the "opStatus" return value from the APFloat 5090 // math calculations, and possibly other variations. 5091 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5092 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5093 if (N1CFP && N2CFP) { 5094 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5095 switch (Opcode) { 5096 case ISD::FADD: 5097 C1.add(C2, APFloat::rmNearestTiesToEven); 5098 return getConstantFP(C1, DL, VT); 5099 case ISD::FSUB: 5100 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5101 return getConstantFP(C1, DL, VT); 5102 case ISD::FMUL: 5103 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5104 return getConstantFP(C1, DL, VT); 5105 case ISD::FDIV: 5106 C1.divide(C2, APFloat::rmNearestTiesToEven); 5107 return getConstantFP(C1, DL, VT); 5108 case ISD::FREM: 5109 C1.mod(C2); 5110 return getConstantFP(C1, DL, VT); 5111 case ISD::FCOPYSIGN: 5112 C1.copySign(C2); 5113 return getConstantFP(C1, DL, VT); 5114 default: break; 5115 } 5116 } 5117 if (N1CFP && Opcode == ISD::FP_ROUND) { 5118 APFloat C1 = N1CFP->getValueAPF(); // make copy 5119 bool Unused; 5120 // This can return overflow, underflow, or inexact; we don't care. 5121 // FIXME need to be more flexible about rounding mode. 5122 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5123 &Unused); 5124 return getConstantFP(C1, DL, VT); 5125 } 5126 5127 switch (Opcode) { 5128 case ISD::FSUB: 5129 // -0.0 - undef --> undef (consistent with "fneg undef") 5130 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5131 return getUNDEF(VT); 5132 LLVM_FALLTHROUGH; 5133 5134 case ISD::FADD: 5135 case ISD::FMUL: 5136 case ISD::FDIV: 5137 case ISD::FREM: 5138 // If both operands are undef, the result is undef. If 1 operand is undef, 5139 // the result is NaN. This should match the behavior of the IR optimizer. 5140 if (N1.isUndef() && N2.isUndef()) 5141 return getUNDEF(VT); 5142 if (N1.isUndef() || N2.isUndef()) 5143 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5144 } 5145 return SDValue(); 5146 } 5147 5148 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5149 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5150 5151 // There's no need to assert on a byte-aligned pointer. All pointers are at 5152 // least byte aligned. 5153 if (A == Align(1)) 5154 return Val; 5155 5156 FoldingSetNodeID ID; 5157 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5158 ID.AddInteger(A.value()); 5159 5160 void *IP = nullptr; 5161 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5162 return SDValue(E, 0); 5163 5164 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5165 Val.getValueType(), A); 5166 createOperands(N, {Val}); 5167 5168 CSEMap.InsertNode(N, IP); 5169 InsertNode(N); 5170 5171 SDValue V(N, 0); 5172 NewSDValueDbgMsg(V, "Creating new node: ", this); 5173 return V; 5174 } 5175 5176 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5177 SDValue N1, SDValue N2) { 5178 SDNodeFlags Flags; 5179 if (Inserter) 5180 Flags = Inserter->getFlags(); 5181 return getNode(Opcode, DL, VT, N1, N2, Flags); 5182 } 5183 5184 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5185 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5186 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5187 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5188 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5189 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5190 5191 // Canonicalize constant to RHS if commutative. 5192 if (TLI->isCommutativeBinOp(Opcode)) { 5193 if (N1C && !N2C) { 5194 std::swap(N1C, N2C); 5195 std::swap(N1, N2); 5196 } else if (N1CFP && !N2CFP) { 5197 std::swap(N1CFP, N2CFP); 5198 std::swap(N1, N2); 5199 } 5200 } 5201 5202 switch (Opcode) { 5203 default: break; 5204 case ISD::TokenFactor: 5205 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5206 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5207 // Fold trivial token factors. 5208 if (N1.getOpcode() == ISD::EntryToken) return N2; 5209 if (N2.getOpcode() == ISD::EntryToken) return N1; 5210 if (N1 == N2) return N1; 5211 break; 5212 case ISD::BUILD_VECTOR: { 5213 // Attempt to simplify BUILD_VECTOR. 5214 SDValue Ops[] = {N1, N2}; 5215 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5216 return V; 5217 break; 5218 } 5219 case ISD::CONCAT_VECTORS: { 5220 SDValue Ops[] = {N1, N2}; 5221 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5222 return V; 5223 break; 5224 } 5225 case ISD::AND: 5226 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5227 assert(N1.getValueType() == N2.getValueType() && 5228 N1.getValueType() == VT && "Binary operator types must match!"); 5229 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5230 // worth handling here. 5231 if (N2C && N2C->isNullValue()) 5232 return N2; 5233 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5234 return N1; 5235 break; 5236 case ISD::OR: 5237 case ISD::XOR: 5238 case ISD::ADD: 5239 case ISD::SUB: 5240 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5241 assert(N1.getValueType() == N2.getValueType() && 5242 N1.getValueType() == VT && "Binary operator types must match!"); 5243 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5244 // it's worth handling here. 5245 if (N2C && N2C->isNullValue()) 5246 return N1; 5247 break; 5248 case ISD::MUL: 5249 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5250 assert(N1.getValueType() == N2.getValueType() && 5251 N1.getValueType() == VT && "Binary operator types must match!"); 5252 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5253 APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue(); 5254 APInt N2CImm = N2C->getAPIntValue(); 5255 return getVScale(DL, VT, MulImm * N2CImm); 5256 } 5257 break; 5258 case ISD::UDIV: 5259 case ISD::UREM: 5260 case ISD::MULHU: 5261 case ISD::MULHS: 5262 case ISD::SDIV: 5263 case ISD::SREM: 5264 case ISD::SADDSAT: 5265 case ISD::SSUBSAT: 5266 case ISD::UADDSAT: 5267 case ISD::USUBSAT: 5268 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5269 assert(N1.getValueType() == N2.getValueType() && 5270 N1.getValueType() == VT && "Binary operator types must match!"); 5271 break; 5272 case ISD::SMIN: 5273 case ISD::UMAX: 5274 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5275 assert(N1.getValueType() == N2.getValueType() && 5276 N1.getValueType() == VT && "Binary operator types must match!"); 5277 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5278 return getNode(ISD::OR, DL, VT, N1, N2); 5279 break; 5280 case ISD::SMAX: 5281 case ISD::UMIN: 5282 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5283 assert(N1.getValueType() == N2.getValueType() && 5284 N1.getValueType() == VT && "Binary operator types must match!"); 5285 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5286 return getNode(ISD::AND, DL, VT, N1, N2); 5287 break; 5288 case ISD::FADD: 5289 case ISD::FSUB: 5290 case ISD::FMUL: 5291 case ISD::FDIV: 5292 case ISD::FREM: 5293 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5294 assert(N1.getValueType() == N2.getValueType() && 5295 N1.getValueType() == VT && "Binary operator types must match!"); 5296 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5297 return V; 5298 break; 5299 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5300 assert(N1.getValueType() == VT && 5301 N1.getValueType().isFloatingPoint() && 5302 N2.getValueType().isFloatingPoint() && 5303 "Invalid FCOPYSIGN!"); 5304 break; 5305 case ISD::SHL: 5306 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5307 APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue(); 5308 APInt ShiftImm = N2C->getAPIntValue(); 5309 return getVScale(DL, VT, MulImm << ShiftImm); 5310 } 5311 LLVM_FALLTHROUGH; 5312 case ISD::SRA: 5313 case ISD::SRL: 5314 if (SDValue V = simplifyShift(N1, N2)) 5315 return V; 5316 LLVM_FALLTHROUGH; 5317 case ISD::ROTL: 5318 case ISD::ROTR: 5319 assert(VT == N1.getValueType() && 5320 "Shift operators return type must be the same as their first arg"); 5321 assert(VT.isInteger() && N2.getValueType().isInteger() && 5322 "Shifts only work on integers"); 5323 assert((!VT.isVector() || VT == N2.getValueType()) && 5324 "Vector shift amounts must be in the same as their first arg"); 5325 // Verify that the shift amount VT is big enough to hold valid shift 5326 // amounts. This catches things like trying to shift an i1024 value by an 5327 // i8, which is easy to fall into in generic code that uses 5328 // TLI.getShiftAmount(). 5329 assert(N2.getValueType().getScalarSizeInBits() >= 5330 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5331 "Invalid use of small shift amount with oversized value!"); 5332 5333 // Always fold shifts of i1 values so the code generator doesn't need to 5334 // handle them. Since we know the size of the shift has to be less than the 5335 // size of the value, the shift/rotate count is guaranteed to be zero. 5336 if (VT == MVT::i1) 5337 return N1; 5338 if (N2C && N2C->isNullValue()) 5339 return N1; 5340 break; 5341 case ISD::FP_ROUND: 5342 assert(VT.isFloatingPoint() && 5343 N1.getValueType().isFloatingPoint() && 5344 VT.bitsLE(N1.getValueType()) && 5345 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5346 "Invalid FP_ROUND!"); 5347 if (N1.getValueType() == VT) return N1; // noop conversion. 5348 break; 5349 case ISD::AssertSext: 5350 case ISD::AssertZext: { 5351 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5352 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5353 assert(VT.isInteger() && EVT.isInteger() && 5354 "Cannot *_EXTEND_INREG FP types"); 5355 assert(!EVT.isVector() && 5356 "AssertSExt/AssertZExt type should be the vector element type " 5357 "rather than the vector type!"); 5358 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5359 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5360 break; 5361 } 5362 case ISD::SIGN_EXTEND_INREG: { 5363 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5364 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5365 assert(VT.isInteger() && EVT.isInteger() && 5366 "Cannot *_EXTEND_INREG FP types"); 5367 assert(EVT.isVector() == VT.isVector() && 5368 "SIGN_EXTEND_INREG type should be vector iff the operand " 5369 "type is vector!"); 5370 assert((!EVT.isVector() || 5371 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5372 "Vector element counts must match in SIGN_EXTEND_INREG"); 5373 assert(EVT.bitsLE(VT) && "Not extending!"); 5374 if (EVT == VT) return N1; // Not actually extending 5375 5376 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5377 unsigned FromBits = EVT.getScalarSizeInBits(); 5378 Val <<= Val.getBitWidth() - FromBits; 5379 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5380 return getConstant(Val, DL, ConstantVT); 5381 }; 5382 5383 if (N1C) { 5384 const APInt &Val = N1C->getAPIntValue(); 5385 return SignExtendInReg(Val, VT); 5386 } 5387 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5388 SmallVector<SDValue, 8> Ops; 5389 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5390 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5391 SDValue Op = N1.getOperand(i); 5392 if (Op.isUndef()) { 5393 Ops.push_back(getUNDEF(OpVT)); 5394 continue; 5395 } 5396 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5397 APInt Val = C->getAPIntValue(); 5398 Ops.push_back(SignExtendInReg(Val, OpVT)); 5399 } 5400 return getBuildVector(VT, DL, Ops); 5401 } 5402 break; 5403 } 5404 case ISD::EXTRACT_VECTOR_ELT: 5405 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5406 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5407 element type of the vector."); 5408 5409 // Extract from an undefined value or using an undefined index is undefined. 5410 if (N1.isUndef() || N2.isUndef()) 5411 return getUNDEF(VT); 5412 5413 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5414 // vectors. For scalable vectors we will provide appropriate support for 5415 // dealing with arbitrary indices. 5416 if (N2C && N1.getValueType().isFixedLengthVector() && 5417 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5418 return getUNDEF(VT); 5419 5420 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5421 // expanding copies of large vectors from registers. This only works for 5422 // fixed length vectors, since we need to know the exact number of 5423 // elements. 5424 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5425 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5426 unsigned Factor = 5427 N1.getOperand(0).getValueType().getVectorNumElements(); 5428 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5429 N1.getOperand(N2C->getZExtValue() / Factor), 5430 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5431 } 5432 5433 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5434 // lowering is expanding large vector constants. 5435 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5436 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5437 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5438 N1.getValueType().isFixedLengthVector()) && 5439 "BUILD_VECTOR used for scalable vectors"); 5440 unsigned Index = 5441 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5442 SDValue Elt = N1.getOperand(Index); 5443 5444 if (VT != Elt.getValueType()) 5445 // If the vector element type is not legal, the BUILD_VECTOR operands 5446 // are promoted and implicitly truncated, and the result implicitly 5447 // extended. Make that explicit here. 5448 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5449 5450 return Elt; 5451 } 5452 5453 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5454 // operations are lowered to scalars. 5455 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5456 // If the indices are the same, return the inserted element else 5457 // if the indices are known different, extract the element from 5458 // the original vector. 5459 SDValue N1Op2 = N1.getOperand(2); 5460 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5461 5462 if (N1Op2C && N2C) { 5463 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5464 if (VT == N1.getOperand(1).getValueType()) 5465 return N1.getOperand(1); 5466 else 5467 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5468 } 5469 5470 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5471 } 5472 } 5473 5474 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5475 // when vector types are scalarized and v1iX is legal. 5476 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5477 // Here we are completely ignoring the extract element index (N2), 5478 // which is fine for fixed width vectors, since any index other than 0 5479 // is undefined anyway. However, this cannot be ignored for scalable 5480 // vectors - in theory we could support this, but we don't want to do this 5481 // without a profitability check. 5482 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5483 N1.getValueType().isFixedLengthVector() && 5484 N1.getValueType().getVectorNumElements() == 1) { 5485 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5486 N1.getOperand(1)); 5487 } 5488 break; 5489 case ISD::EXTRACT_ELEMENT: 5490 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5491 assert(!N1.getValueType().isVector() && !VT.isVector() && 5492 (N1.getValueType().isInteger() == VT.isInteger()) && 5493 N1.getValueType() != VT && 5494 "Wrong types for EXTRACT_ELEMENT!"); 5495 5496 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5497 // 64-bit integers into 32-bit parts. Instead of building the extract of 5498 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5499 if (N1.getOpcode() == ISD::BUILD_PAIR) 5500 return N1.getOperand(N2C->getZExtValue()); 5501 5502 // EXTRACT_ELEMENT of a constant int is also very common. 5503 if (N1C) { 5504 unsigned ElementSize = VT.getSizeInBits(); 5505 unsigned Shift = ElementSize * N2C->getZExtValue(); 5506 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift); 5507 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT); 5508 } 5509 break; 5510 case ISD::EXTRACT_SUBVECTOR: 5511 EVT N1VT = N1.getValueType(); 5512 assert(VT.isVector() && N1VT.isVector() && 5513 "Extract subvector VTs must be vectors!"); 5514 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5515 "Extract subvector VTs must have the same element type!"); 5516 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5517 "Cannot extract a scalable vector from a fixed length vector!"); 5518 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5519 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5520 "Extract subvector must be from larger vector to smaller vector!"); 5521 assert(N2C && "Extract subvector index must be a constant"); 5522 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5523 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5524 N1VT.getVectorMinNumElements()) && 5525 "Extract subvector overflow!"); 5526 assert(N2C->getAPIntValue().getBitWidth() == 5527 TLI->getVectorIdxTy(getDataLayout()) 5528 .getSizeInBits() 5529 .getFixedSize() && 5530 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5531 5532 // Trivial extraction. 5533 if (VT == N1VT) 5534 return N1; 5535 5536 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5537 if (N1.isUndef()) 5538 return getUNDEF(VT); 5539 5540 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5541 // the concat have the same type as the extract. 5542 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5543 VT == N1.getOperand(0).getValueType()) { 5544 unsigned Factor = VT.getVectorMinNumElements(); 5545 return N1.getOperand(N2C->getZExtValue() / Factor); 5546 } 5547 5548 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5549 // during shuffle legalization. 5550 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5551 VT == N1.getOperand(1).getValueType()) 5552 return N1.getOperand(1); 5553 break; 5554 } 5555 5556 // Perform trivial constant folding. 5557 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5558 return SV; 5559 5560 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5561 return V; 5562 5563 // Canonicalize an UNDEF to the RHS, even over a constant. 5564 if (N1.isUndef()) { 5565 if (TLI->isCommutativeBinOp(Opcode)) { 5566 std::swap(N1, N2); 5567 } else { 5568 switch (Opcode) { 5569 case ISD::SIGN_EXTEND_INREG: 5570 case ISD::SUB: 5571 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5572 case ISD::UDIV: 5573 case ISD::SDIV: 5574 case ISD::UREM: 5575 case ISD::SREM: 5576 case ISD::SSUBSAT: 5577 case ISD::USUBSAT: 5578 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5579 } 5580 } 5581 } 5582 5583 // Fold a bunch of operators when the RHS is undef. 5584 if (N2.isUndef()) { 5585 switch (Opcode) { 5586 case ISD::XOR: 5587 if (N1.isUndef()) 5588 // Handle undef ^ undef -> 0 special case. This is a common 5589 // idiom (misuse). 5590 return getConstant(0, DL, VT); 5591 LLVM_FALLTHROUGH; 5592 case ISD::ADD: 5593 case ISD::SUB: 5594 case ISD::UDIV: 5595 case ISD::SDIV: 5596 case ISD::UREM: 5597 case ISD::SREM: 5598 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5599 case ISD::MUL: 5600 case ISD::AND: 5601 case ISD::SSUBSAT: 5602 case ISD::USUBSAT: 5603 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5604 case ISD::OR: 5605 case ISD::SADDSAT: 5606 case ISD::UADDSAT: 5607 return getAllOnesConstant(DL, VT); 5608 } 5609 } 5610 5611 // Memoize this node if possible. 5612 SDNode *N; 5613 SDVTList VTs = getVTList(VT); 5614 SDValue Ops[] = {N1, N2}; 5615 if (VT != MVT::Glue) { 5616 FoldingSetNodeID ID; 5617 AddNodeIDNode(ID, Opcode, VTs, Ops); 5618 void *IP = nullptr; 5619 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5620 E->intersectFlagsWith(Flags); 5621 return SDValue(E, 0); 5622 } 5623 5624 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5625 N->setFlags(Flags); 5626 createOperands(N, Ops); 5627 CSEMap.InsertNode(N, IP); 5628 } else { 5629 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5630 createOperands(N, Ops); 5631 } 5632 5633 InsertNode(N); 5634 SDValue V = SDValue(N, 0); 5635 NewSDValueDbgMsg(V, "Creating new node: ", this); 5636 return V; 5637 } 5638 5639 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5640 SDValue N1, SDValue N2, SDValue N3) { 5641 SDNodeFlags Flags; 5642 if (Inserter) 5643 Flags = Inserter->getFlags(); 5644 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5645 } 5646 5647 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5648 SDValue N1, SDValue N2, SDValue N3, 5649 const SDNodeFlags Flags) { 5650 // Perform various simplifications. 5651 switch (Opcode) { 5652 case ISD::FMA: { 5653 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5654 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5655 N3.getValueType() == VT && "FMA types must match!"); 5656 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5657 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5658 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5659 if (N1CFP && N2CFP && N3CFP) { 5660 APFloat V1 = N1CFP->getValueAPF(); 5661 const APFloat &V2 = N2CFP->getValueAPF(); 5662 const APFloat &V3 = N3CFP->getValueAPF(); 5663 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5664 return getConstantFP(V1, DL, VT); 5665 } 5666 break; 5667 } 5668 case ISD::BUILD_VECTOR: { 5669 // Attempt to simplify BUILD_VECTOR. 5670 SDValue Ops[] = {N1, N2, N3}; 5671 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5672 return V; 5673 break; 5674 } 5675 case ISD::CONCAT_VECTORS: { 5676 SDValue Ops[] = {N1, N2, N3}; 5677 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5678 return V; 5679 break; 5680 } 5681 case ISD::SETCC: { 5682 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5683 assert(N1.getValueType() == N2.getValueType() && 5684 "SETCC operands must have the same type!"); 5685 assert(VT.isVector() == N1.getValueType().isVector() && 5686 "SETCC type should be vector iff the operand type is vector!"); 5687 assert((!VT.isVector() || VT.getVectorElementCount() == 5688 N1.getValueType().getVectorElementCount()) && 5689 "SETCC vector element counts must match!"); 5690 // Use FoldSetCC to simplify SETCC's. 5691 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5692 return V; 5693 // Vector constant folding. 5694 SDValue Ops[] = {N1, N2, N3}; 5695 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5696 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5697 return V; 5698 } 5699 break; 5700 } 5701 case ISD::SELECT: 5702 case ISD::VSELECT: 5703 if (SDValue V = simplifySelect(N1, N2, N3)) 5704 return V; 5705 break; 5706 case ISD::VECTOR_SHUFFLE: 5707 llvm_unreachable("should use getVectorShuffle constructor!"); 5708 case ISD::INSERT_VECTOR_ELT: { 5709 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5710 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 5711 // for scalable vectors where we will generate appropriate code to 5712 // deal with out-of-bounds cases correctly. 5713 if (N3C && N1.getValueType().isFixedLengthVector() && 5714 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5715 return getUNDEF(VT); 5716 5717 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 5718 if (N3.isUndef()) 5719 return getUNDEF(VT); 5720 5721 // If the inserted element is an UNDEF, just use the input vector. 5722 if (N2.isUndef()) 5723 return N1; 5724 5725 break; 5726 } 5727 case ISD::INSERT_SUBVECTOR: { 5728 // Inserting undef into undef is still undef. 5729 if (N1.isUndef() && N2.isUndef()) 5730 return getUNDEF(VT); 5731 5732 EVT N2VT = N2.getValueType(); 5733 assert(VT == N1.getValueType() && 5734 "Dest and insert subvector source types must match!"); 5735 assert(VT.isVector() && N2VT.isVector() && 5736 "Insert subvector VTs must be vectors!"); 5737 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 5738 "Cannot insert a scalable vector into a fixed length vector!"); 5739 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5740 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 5741 "Insert subvector must be from smaller vector to larger vector!"); 5742 assert(isa<ConstantSDNode>(N3) && 5743 "Insert subvector index must be constant"); 5744 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5745 (N2VT.getVectorMinNumElements() + 5746 cast<ConstantSDNode>(N3)->getZExtValue()) <= 5747 VT.getVectorMinNumElements()) && 5748 "Insert subvector overflow!"); 5749 5750 // Trivial insertion. 5751 if (VT == N2VT) 5752 return N2; 5753 5754 // If this is an insert of an extracted vector into an undef vector, we 5755 // can just use the input to the extract. 5756 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5757 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 5758 return N2.getOperand(0); 5759 break; 5760 } 5761 case ISD::BITCAST: 5762 // Fold bit_convert nodes from a type to themselves. 5763 if (N1.getValueType() == VT) 5764 return N1; 5765 break; 5766 } 5767 5768 // Memoize node if it doesn't produce a flag. 5769 SDNode *N; 5770 SDVTList VTs = getVTList(VT); 5771 SDValue Ops[] = {N1, N2, N3}; 5772 if (VT != MVT::Glue) { 5773 FoldingSetNodeID ID; 5774 AddNodeIDNode(ID, Opcode, VTs, Ops); 5775 void *IP = nullptr; 5776 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5777 E->intersectFlagsWith(Flags); 5778 return SDValue(E, 0); 5779 } 5780 5781 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5782 N->setFlags(Flags); 5783 createOperands(N, Ops); 5784 CSEMap.InsertNode(N, IP); 5785 } else { 5786 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5787 createOperands(N, Ops); 5788 } 5789 5790 InsertNode(N); 5791 SDValue V = SDValue(N, 0); 5792 NewSDValueDbgMsg(V, "Creating new node: ", this); 5793 return V; 5794 } 5795 5796 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5797 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5798 SDValue Ops[] = { N1, N2, N3, N4 }; 5799 return getNode(Opcode, DL, VT, Ops); 5800 } 5801 5802 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5803 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5804 SDValue N5) { 5805 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5806 return getNode(Opcode, DL, VT, Ops); 5807 } 5808 5809 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 5810 /// the incoming stack arguments to be loaded from the stack. 5811 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 5812 SmallVector<SDValue, 8> ArgChains; 5813 5814 // Include the original chain at the beginning of the list. When this is 5815 // used by target LowerCall hooks, this helps legalize find the 5816 // CALLSEQ_BEGIN node. 5817 ArgChains.push_back(Chain); 5818 5819 // Add a chain value for each stack argument. 5820 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 5821 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 5822 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5823 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5824 if (FI->getIndex() < 0) 5825 ArgChains.push_back(SDValue(L, 1)); 5826 5827 // Build a tokenfactor for all the chains. 5828 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5829 } 5830 5831 /// getMemsetValue - Vectorized representation of the memset value 5832 /// operand. 5833 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 5834 const SDLoc &dl) { 5835 assert(!Value.isUndef()); 5836 5837 unsigned NumBits = VT.getScalarSizeInBits(); 5838 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 5839 assert(C->getAPIntValue().getBitWidth() == 8); 5840 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 5841 if (VT.isInteger()) { 5842 bool IsOpaque = VT.getSizeInBits() > 64 || 5843 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 5844 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 5845 } 5846 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 5847 VT); 5848 } 5849 5850 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 5851 EVT IntVT = VT.getScalarType(); 5852 if (!IntVT.isInteger()) 5853 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 5854 5855 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 5856 if (NumBits > 8) { 5857 // Use a multiplication with 0x010101... to extend the input to the 5858 // required length. 5859 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 5860 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 5861 DAG.getConstant(Magic, dl, IntVT)); 5862 } 5863 5864 if (VT != Value.getValueType() && !VT.isInteger()) 5865 Value = DAG.getBitcast(VT.getScalarType(), Value); 5866 if (VT != Value.getValueType()) 5867 Value = DAG.getSplatBuildVector(VT, dl, Value); 5868 5869 return Value; 5870 } 5871 5872 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 5873 /// used when a memcpy is turned into a memset when the source is a constant 5874 /// string ptr. 5875 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 5876 const TargetLowering &TLI, 5877 const ConstantDataArraySlice &Slice) { 5878 // Handle vector with all elements zero. 5879 if (Slice.Array == nullptr) { 5880 if (VT.isInteger()) 5881 return DAG.getConstant(0, dl, VT); 5882 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 5883 return DAG.getConstantFP(0.0, dl, VT); 5884 else if (VT.isVector()) { 5885 unsigned NumElts = VT.getVectorNumElements(); 5886 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 5887 return DAG.getNode(ISD::BITCAST, dl, VT, 5888 DAG.getConstant(0, dl, 5889 EVT::getVectorVT(*DAG.getContext(), 5890 EltVT, NumElts))); 5891 } else 5892 llvm_unreachable("Expected type!"); 5893 } 5894 5895 assert(!VT.isVector() && "Can't handle vector type here!"); 5896 unsigned NumVTBits = VT.getSizeInBits(); 5897 unsigned NumVTBytes = NumVTBits / 8; 5898 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 5899 5900 APInt Val(NumVTBits, 0); 5901 if (DAG.getDataLayout().isLittleEndian()) { 5902 for (unsigned i = 0; i != NumBytes; ++i) 5903 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 5904 } else { 5905 for (unsigned i = 0; i != NumBytes; ++i) 5906 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 5907 } 5908 5909 // If the "cost" of materializing the integer immediate is less than the cost 5910 // of a load, then it is cost effective to turn the load into the immediate. 5911 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 5912 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 5913 return DAG.getConstant(Val, dl, VT); 5914 return SDValue(nullptr, 0); 5915 } 5916 5917 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 5918 const SDLoc &DL, 5919 const SDNodeFlags Flags) { 5920 EVT VT = Base.getValueType(); 5921 SDValue Index; 5922 5923 if (Offset.isScalable()) 5924 Index = getVScale(DL, Base.getValueType(), 5925 APInt(Base.getValueSizeInBits().getFixedSize(), 5926 Offset.getKnownMinSize())); 5927 else 5928 Index = getConstant(Offset.getFixedSize(), DL, VT); 5929 5930 return getMemBasePlusOffset(Base, Index, DL, Flags); 5931 } 5932 5933 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 5934 const SDLoc &DL, 5935 const SDNodeFlags Flags) { 5936 assert(Offset.getValueType().isInteger()); 5937 EVT BasePtrVT = Ptr.getValueType(); 5938 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 5939 } 5940 5941 /// Returns true if memcpy source is constant data. 5942 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 5943 uint64_t SrcDelta = 0; 5944 GlobalAddressSDNode *G = nullptr; 5945 if (Src.getOpcode() == ISD::GlobalAddress) 5946 G = cast<GlobalAddressSDNode>(Src); 5947 else if (Src.getOpcode() == ISD::ADD && 5948 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 5949 Src.getOperand(1).getOpcode() == ISD::Constant) { 5950 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 5951 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 5952 } 5953 if (!G) 5954 return false; 5955 5956 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 5957 SrcDelta + G->getOffset()); 5958 } 5959 5960 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 5961 SelectionDAG &DAG) { 5962 // On Darwin, -Os means optimize for size without hurting performance, so 5963 // only really optimize for size when -Oz (MinSize) is used. 5964 if (MF.getTarget().getTargetTriple().isOSDarwin()) 5965 return MF.getFunction().hasMinSize(); 5966 return DAG.shouldOptForSize(); 5967 } 5968 5969 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 5970 SmallVector<SDValue, 32> &OutChains, unsigned From, 5971 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 5972 SmallVector<SDValue, 16> &OutStoreChains) { 5973 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 5974 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 5975 SmallVector<SDValue, 16> GluedLoadChains; 5976 for (unsigned i = From; i < To; ++i) { 5977 OutChains.push_back(OutLoadChains[i]); 5978 GluedLoadChains.push_back(OutLoadChains[i]); 5979 } 5980 5981 // Chain for all loads. 5982 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 5983 GluedLoadChains); 5984 5985 for (unsigned i = From; i < To; ++i) { 5986 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 5987 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 5988 ST->getBasePtr(), ST->getMemoryVT(), 5989 ST->getMemOperand()); 5990 OutChains.push_back(NewStore); 5991 } 5992 } 5993 5994 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 5995 SDValue Chain, SDValue Dst, SDValue Src, 5996 uint64_t Size, Align Alignment, 5997 bool isVol, bool AlwaysInline, 5998 MachinePointerInfo DstPtrInfo, 5999 MachinePointerInfo SrcPtrInfo) { 6000 // Turn a memcpy of undef to nop. 6001 // FIXME: We need to honor volatile even is Src is undef. 6002 if (Src.isUndef()) 6003 return Chain; 6004 6005 // Expand memcpy to a series of load and store ops if the size operand falls 6006 // below a certain threshold. 6007 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6008 // rather than maybe a humongous number of loads and stores. 6009 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6010 const DataLayout &DL = DAG.getDataLayout(); 6011 LLVMContext &C = *DAG.getContext(); 6012 std::vector<EVT> MemOps; 6013 bool DstAlignCanChange = false; 6014 MachineFunction &MF = DAG.getMachineFunction(); 6015 MachineFrameInfo &MFI = MF.getFrameInfo(); 6016 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6017 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6018 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6019 DstAlignCanChange = true; 6020 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6021 if (!SrcAlign || Alignment > *SrcAlign) 6022 SrcAlign = Alignment; 6023 assert(SrcAlign && "SrcAlign must be set"); 6024 ConstantDataArraySlice Slice; 6025 // If marked as volatile, perform a copy even when marked as constant. 6026 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6027 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6028 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6029 const MemOp Op = isZeroConstant 6030 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6031 /*IsZeroMemset*/ true, isVol) 6032 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6033 *SrcAlign, isVol, CopyFromConstant); 6034 if (!TLI.findOptimalMemOpLowering( 6035 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6036 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6037 return SDValue(); 6038 6039 if (DstAlignCanChange) { 6040 Type *Ty = MemOps[0].getTypeForEVT(C); 6041 Align NewAlign = DL.getABITypeAlign(Ty); 6042 6043 // Don't promote to an alignment that would require dynamic stack 6044 // realignment. 6045 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6046 if (!TRI->needsStackRealignment(MF)) 6047 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6048 NewAlign = NewAlign / 2; 6049 6050 if (NewAlign > Alignment) { 6051 // Give the stack frame object a larger alignment if needed. 6052 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6053 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6054 Alignment = NewAlign; 6055 } 6056 } 6057 6058 MachineMemOperand::Flags MMOFlags = 6059 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6060 SmallVector<SDValue, 16> OutLoadChains; 6061 SmallVector<SDValue, 16> OutStoreChains; 6062 SmallVector<SDValue, 32> OutChains; 6063 unsigned NumMemOps = MemOps.size(); 6064 uint64_t SrcOff = 0, DstOff = 0; 6065 for (unsigned i = 0; i != NumMemOps; ++i) { 6066 EVT VT = MemOps[i]; 6067 unsigned VTSize = VT.getSizeInBits() / 8; 6068 SDValue Value, Store; 6069 6070 if (VTSize > Size) { 6071 // Issuing an unaligned load / store pair that overlaps with the previous 6072 // pair. Adjust the offset accordingly. 6073 assert(i == NumMemOps-1 && i != 0); 6074 SrcOff -= VTSize - Size; 6075 DstOff -= VTSize - Size; 6076 } 6077 6078 if (CopyFromConstant && 6079 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6080 // It's unlikely a store of a vector immediate can be done in a single 6081 // instruction. It would require a load from a constantpool first. 6082 // We only handle zero vectors here. 6083 // FIXME: Handle other cases where store of vector immediate is done in 6084 // a single instruction. 6085 ConstantDataArraySlice SubSlice; 6086 if (SrcOff < Slice.Length) { 6087 SubSlice = Slice; 6088 SubSlice.move(SrcOff); 6089 } else { 6090 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6091 SubSlice.Array = nullptr; 6092 SubSlice.Offset = 0; 6093 SubSlice.Length = VTSize; 6094 } 6095 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6096 if (Value.getNode()) { 6097 Store = DAG.getStore( 6098 Chain, dl, Value, 6099 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6100 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6101 OutChains.push_back(Store); 6102 } 6103 } 6104 6105 if (!Store.getNode()) { 6106 // The type might not be legal for the target. This should only happen 6107 // if the type is smaller than a legal type, as on PPC, so the right 6108 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6109 // to Load/Store if NVT==VT. 6110 // FIXME does the case above also need this? 6111 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6112 assert(NVT.bitsGE(VT)); 6113 6114 bool isDereferenceable = 6115 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6116 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6117 if (isDereferenceable) 6118 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6119 6120 Value = DAG.getExtLoad( 6121 ISD::EXTLOAD, dl, NVT, Chain, 6122 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6123 SrcPtrInfo.getWithOffset(SrcOff), VT, 6124 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6125 OutLoadChains.push_back(Value.getValue(1)); 6126 6127 Store = DAG.getTruncStore( 6128 Chain, dl, Value, 6129 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6130 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6131 OutStoreChains.push_back(Store); 6132 } 6133 SrcOff += VTSize; 6134 DstOff += VTSize; 6135 Size -= VTSize; 6136 } 6137 6138 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6139 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6140 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6141 6142 if (NumLdStInMemcpy) { 6143 // It may be that memcpy might be converted to memset if it's memcpy 6144 // of constants. In such a case, we won't have loads and stores, but 6145 // just stores. In the absence of loads, there is nothing to gang up. 6146 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6147 // If target does not care, just leave as it. 6148 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6149 OutChains.push_back(OutLoadChains[i]); 6150 OutChains.push_back(OutStoreChains[i]); 6151 } 6152 } else { 6153 // Ld/St less than/equal limit set by target. 6154 if (NumLdStInMemcpy <= GluedLdStLimit) { 6155 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6156 NumLdStInMemcpy, OutLoadChains, 6157 OutStoreChains); 6158 } else { 6159 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6160 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6161 unsigned GlueIter = 0; 6162 6163 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6164 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6165 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6166 6167 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6168 OutLoadChains, OutStoreChains); 6169 GlueIter += GluedLdStLimit; 6170 } 6171 6172 // Residual ld/st. 6173 if (RemainingLdStInMemcpy) { 6174 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6175 RemainingLdStInMemcpy, OutLoadChains, 6176 OutStoreChains); 6177 } 6178 } 6179 } 6180 } 6181 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6182 } 6183 6184 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6185 SDValue Chain, SDValue Dst, SDValue Src, 6186 uint64_t Size, Align Alignment, 6187 bool isVol, bool AlwaysInline, 6188 MachinePointerInfo DstPtrInfo, 6189 MachinePointerInfo SrcPtrInfo) { 6190 // Turn a memmove of undef to nop. 6191 // FIXME: We need to honor volatile even is Src is undef. 6192 if (Src.isUndef()) 6193 return Chain; 6194 6195 // Expand memmove to a series of load and store ops if the size operand falls 6196 // below a certain threshold. 6197 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6198 const DataLayout &DL = DAG.getDataLayout(); 6199 LLVMContext &C = *DAG.getContext(); 6200 std::vector<EVT> MemOps; 6201 bool DstAlignCanChange = false; 6202 MachineFunction &MF = DAG.getMachineFunction(); 6203 MachineFrameInfo &MFI = MF.getFrameInfo(); 6204 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6205 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6206 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6207 DstAlignCanChange = true; 6208 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6209 if (!SrcAlign || Alignment > *SrcAlign) 6210 SrcAlign = Alignment; 6211 assert(SrcAlign && "SrcAlign must be set"); 6212 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6213 if (!TLI.findOptimalMemOpLowering( 6214 MemOps, Limit, 6215 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6216 /*IsVolatile*/ true), 6217 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6218 MF.getFunction().getAttributes())) 6219 return SDValue(); 6220 6221 if (DstAlignCanChange) { 6222 Type *Ty = MemOps[0].getTypeForEVT(C); 6223 Align NewAlign = DL.getABITypeAlign(Ty); 6224 if (NewAlign > Alignment) { 6225 // Give the stack frame object a larger alignment if needed. 6226 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6227 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6228 Alignment = NewAlign; 6229 } 6230 } 6231 6232 MachineMemOperand::Flags MMOFlags = 6233 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6234 uint64_t SrcOff = 0, DstOff = 0; 6235 SmallVector<SDValue, 8> LoadValues; 6236 SmallVector<SDValue, 8> LoadChains; 6237 SmallVector<SDValue, 8> OutChains; 6238 unsigned NumMemOps = MemOps.size(); 6239 for (unsigned i = 0; i < NumMemOps; i++) { 6240 EVT VT = MemOps[i]; 6241 unsigned VTSize = VT.getSizeInBits() / 8; 6242 SDValue Value; 6243 6244 bool isDereferenceable = 6245 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6246 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6247 if (isDereferenceable) 6248 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6249 6250 Value = 6251 DAG.getLoad(VT, dl, Chain, 6252 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6253 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6254 LoadValues.push_back(Value); 6255 LoadChains.push_back(Value.getValue(1)); 6256 SrcOff += VTSize; 6257 } 6258 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6259 OutChains.clear(); 6260 for (unsigned i = 0; i < NumMemOps; i++) { 6261 EVT VT = MemOps[i]; 6262 unsigned VTSize = VT.getSizeInBits() / 8; 6263 SDValue Store; 6264 6265 Store = 6266 DAG.getStore(Chain, dl, LoadValues[i], 6267 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6268 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6269 OutChains.push_back(Store); 6270 DstOff += VTSize; 6271 } 6272 6273 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6274 } 6275 6276 /// Lower the call to 'memset' intrinsic function into a series of store 6277 /// operations. 6278 /// 6279 /// \param DAG Selection DAG where lowered code is placed. 6280 /// \param dl Link to corresponding IR location. 6281 /// \param Chain Control flow dependency. 6282 /// \param Dst Pointer to destination memory location. 6283 /// \param Src Value of byte to write into the memory. 6284 /// \param Size Number of bytes to write. 6285 /// \param Alignment Alignment of the destination in bytes. 6286 /// \param isVol True if destination is volatile. 6287 /// \param DstPtrInfo IR information on the memory pointer. 6288 /// \returns New head in the control flow, if lowering was successful, empty 6289 /// SDValue otherwise. 6290 /// 6291 /// The function tries to replace 'llvm.memset' intrinsic with several store 6292 /// operations and value calculation code. This is usually profitable for small 6293 /// memory size. 6294 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6295 SDValue Chain, SDValue Dst, SDValue Src, 6296 uint64_t Size, Align Alignment, bool isVol, 6297 MachinePointerInfo DstPtrInfo) { 6298 // Turn a memset of undef to nop. 6299 // FIXME: We need to honor volatile even is Src is undef. 6300 if (Src.isUndef()) 6301 return Chain; 6302 6303 // Expand memset to a series of load/store ops if the size operand 6304 // falls below a certain threshold. 6305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6306 std::vector<EVT> MemOps; 6307 bool DstAlignCanChange = false; 6308 MachineFunction &MF = DAG.getMachineFunction(); 6309 MachineFrameInfo &MFI = MF.getFrameInfo(); 6310 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6311 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6312 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6313 DstAlignCanChange = true; 6314 bool IsZeroVal = 6315 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6316 if (!TLI.findOptimalMemOpLowering( 6317 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6318 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6319 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6320 return SDValue(); 6321 6322 if (DstAlignCanChange) { 6323 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6324 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6325 if (NewAlign > Alignment) { 6326 // Give the stack frame object a larger alignment if needed. 6327 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6328 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6329 Alignment = NewAlign; 6330 } 6331 } 6332 6333 SmallVector<SDValue, 8> OutChains; 6334 uint64_t DstOff = 0; 6335 unsigned NumMemOps = MemOps.size(); 6336 6337 // Find the largest store and generate the bit pattern for it. 6338 EVT LargestVT = MemOps[0]; 6339 for (unsigned i = 1; i < NumMemOps; i++) 6340 if (MemOps[i].bitsGT(LargestVT)) 6341 LargestVT = MemOps[i]; 6342 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6343 6344 for (unsigned i = 0; i < NumMemOps; i++) { 6345 EVT VT = MemOps[i]; 6346 unsigned VTSize = VT.getSizeInBits() / 8; 6347 if (VTSize > Size) { 6348 // Issuing an unaligned load / store pair that overlaps with the previous 6349 // pair. Adjust the offset accordingly. 6350 assert(i == NumMemOps-1 && i != 0); 6351 DstOff -= VTSize - Size; 6352 } 6353 6354 // If this store is smaller than the largest store see whether we can get 6355 // the smaller value for free with a truncate. 6356 SDValue Value = MemSetValue; 6357 if (VT.bitsLT(LargestVT)) { 6358 if (!LargestVT.isVector() && !VT.isVector() && 6359 TLI.isTruncateFree(LargestVT, VT)) 6360 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6361 else 6362 Value = getMemsetValue(Src, VT, DAG, dl); 6363 } 6364 assert(Value.getValueType() == VT && "Value with wrong type."); 6365 SDValue Store = DAG.getStore( 6366 Chain, dl, Value, 6367 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6368 DstPtrInfo.getWithOffset(DstOff), Alignment, 6369 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6370 OutChains.push_back(Store); 6371 DstOff += VT.getSizeInBits() / 8; 6372 Size -= VTSize; 6373 } 6374 6375 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6376 } 6377 6378 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6379 unsigned AS) { 6380 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6381 // pointer operands can be losslessly bitcasted to pointers of address space 0 6382 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6383 report_fatal_error("cannot lower memory intrinsic in address space " + 6384 Twine(AS)); 6385 } 6386 } 6387 6388 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6389 SDValue Src, SDValue Size, Align Alignment, 6390 bool isVol, bool AlwaysInline, bool isTailCall, 6391 MachinePointerInfo DstPtrInfo, 6392 MachinePointerInfo SrcPtrInfo) { 6393 // Check to see if we should lower the memcpy to loads and stores first. 6394 // For cases within the target-specified limits, this is the best choice. 6395 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6396 if (ConstantSize) { 6397 // Memcpy with size zero? Just return the original chain. 6398 if (ConstantSize->isNullValue()) 6399 return Chain; 6400 6401 SDValue Result = getMemcpyLoadsAndStores( 6402 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6403 isVol, false, DstPtrInfo, SrcPtrInfo); 6404 if (Result.getNode()) 6405 return Result; 6406 } 6407 6408 // Then check to see if we should lower the memcpy with target-specific 6409 // code. If the target chooses to do this, this is the next best. 6410 if (TSI) { 6411 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6412 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6413 DstPtrInfo, SrcPtrInfo); 6414 if (Result.getNode()) 6415 return Result; 6416 } 6417 6418 // If we really need inline code and the target declined to provide it, 6419 // use a (potentially long) sequence of loads and stores. 6420 if (AlwaysInline) { 6421 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6422 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6423 ConstantSize->getZExtValue(), Alignment, 6424 isVol, true, DstPtrInfo, SrcPtrInfo); 6425 } 6426 6427 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6428 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6429 6430 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6431 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6432 // respect volatile, so they may do things like read or write memory 6433 // beyond the given memory regions. But fixing this isn't easy, and most 6434 // people don't care. 6435 6436 // Emit a library call. 6437 TargetLowering::ArgListTy Args; 6438 TargetLowering::ArgListEntry Entry; 6439 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6440 Entry.Node = Dst; Args.push_back(Entry); 6441 Entry.Node = Src; Args.push_back(Entry); 6442 6443 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6444 Entry.Node = Size; Args.push_back(Entry); 6445 // FIXME: pass in SDLoc 6446 TargetLowering::CallLoweringInfo CLI(*this); 6447 CLI.setDebugLoc(dl) 6448 .setChain(Chain) 6449 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6450 Dst.getValueType().getTypeForEVT(*getContext()), 6451 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6452 TLI->getPointerTy(getDataLayout())), 6453 std::move(Args)) 6454 .setDiscardResult() 6455 .setTailCall(isTailCall); 6456 6457 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6458 return CallResult.second; 6459 } 6460 6461 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6462 SDValue Dst, unsigned DstAlign, 6463 SDValue Src, unsigned SrcAlign, 6464 SDValue Size, Type *SizeTy, 6465 unsigned ElemSz, bool isTailCall, 6466 MachinePointerInfo DstPtrInfo, 6467 MachinePointerInfo SrcPtrInfo) { 6468 // Emit a library call. 6469 TargetLowering::ArgListTy Args; 6470 TargetLowering::ArgListEntry Entry; 6471 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6472 Entry.Node = Dst; 6473 Args.push_back(Entry); 6474 6475 Entry.Node = Src; 6476 Args.push_back(Entry); 6477 6478 Entry.Ty = SizeTy; 6479 Entry.Node = Size; 6480 Args.push_back(Entry); 6481 6482 RTLIB::Libcall LibraryCall = 6483 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6484 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6485 report_fatal_error("Unsupported element size"); 6486 6487 TargetLowering::CallLoweringInfo CLI(*this); 6488 CLI.setDebugLoc(dl) 6489 .setChain(Chain) 6490 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6491 Type::getVoidTy(*getContext()), 6492 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6493 TLI->getPointerTy(getDataLayout())), 6494 std::move(Args)) 6495 .setDiscardResult() 6496 .setTailCall(isTailCall); 6497 6498 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6499 return CallResult.second; 6500 } 6501 6502 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6503 SDValue Src, SDValue Size, Align Alignment, 6504 bool isVol, bool isTailCall, 6505 MachinePointerInfo DstPtrInfo, 6506 MachinePointerInfo SrcPtrInfo) { 6507 // Check to see if we should lower the memmove to loads and stores first. 6508 // For cases within the target-specified limits, this is the best choice. 6509 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6510 if (ConstantSize) { 6511 // Memmove with size zero? Just return the original chain. 6512 if (ConstantSize->isNullValue()) 6513 return Chain; 6514 6515 SDValue Result = getMemmoveLoadsAndStores( 6516 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6517 isVol, false, DstPtrInfo, SrcPtrInfo); 6518 if (Result.getNode()) 6519 return Result; 6520 } 6521 6522 // Then check to see if we should lower the memmove with target-specific 6523 // code. If the target chooses to do this, this is the next best. 6524 if (TSI) { 6525 SDValue Result = 6526 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6527 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6528 if (Result.getNode()) 6529 return Result; 6530 } 6531 6532 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6533 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6534 6535 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6536 // not be safe. See memcpy above for more details. 6537 6538 // Emit a library call. 6539 TargetLowering::ArgListTy Args; 6540 TargetLowering::ArgListEntry Entry; 6541 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6542 Entry.Node = Dst; Args.push_back(Entry); 6543 Entry.Node = Src; Args.push_back(Entry); 6544 6545 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6546 Entry.Node = Size; Args.push_back(Entry); 6547 // FIXME: pass in SDLoc 6548 TargetLowering::CallLoweringInfo CLI(*this); 6549 CLI.setDebugLoc(dl) 6550 .setChain(Chain) 6551 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6552 Dst.getValueType().getTypeForEVT(*getContext()), 6553 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6554 TLI->getPointerTy(getDataLayout())), 6555 std::move(Args)) 6556 .setDiscardResult() 6557 .setTailCall(isTailCall); 6558 6559 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6560 return CallResult.second; 6561 } 6562 6563 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6564 SDValue Dst, unsigned DstAlign, 6565 SDValue Src, unsigned SrcAlign, 6566 SDValue Size, Type *SizeTy, 6567 unsigned ElemSz, bool isTailCall, 6568 MachinePointerInfo DstPtrInfo, 6569 MachinePointerInfo SrcPtrInfo) { 6570 // Emit a library call. 6571 TargetLowering::ArgListTy Args; 6572 TargetLowering::ArgListEntry Entry; 6573 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6574 Entry.Node = Dst; 6575 Args.push_back(Entry); 6576 6577 Entry.Node = Src; 6578 Args.push_back(Entry); 6579 6580 Entry.Ty = SizeTy; 6581 Entry.Node = Size; 6582 Args.push_back(Entry); 6583 6584 RTLIB::Libcall LibraryCall = 6585 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6586 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6587 report_fatal_error("Unsupported element size"); 6588 6589 TargetLowering::CallLoweringInfo CLI(*this); 6590 CLI.setDebugLoc(dl) 6591 .setChain(Chain) 6592 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6593 Type::getVoidTy(*getContext()), 6594 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6595 TLI->getPointerTy(getDataLayout())), 6596 std::move(Args)) 6597 .setDiscardResult() 6598 .setTailCall(isTailCall); 6599 6600 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6601 return CallResult.second; 6602 } 6603 6604 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6605 SDValue Src, SDValue Size, Align Alignment, 6606 bool isVol, bool isTailCall, 6607 MachinePointerInfo DstPtrInfo) { 6608 // Check to see if we should lower the memset to stores first. 6609 // For cases within the target-specified limits, this is the best choice. 6610 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6611 if (ConstantSize) { 6612 // Memset with size zero? Just return the original chain. 6613 if (ConstantSize->isNullValue()) 6614 return Chain; 6615 6616 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6617 ConstantSize->getZExtValue(), Alignment, 6618 isVol, DstPtrInfo); 6619 6620 if (Result.getNode()) 6621 return Result; 6622 } 6623 6624 // Then check to see if we should lower the memset with target-specific 6625 // code. If the target chooses to do this, this is the next best. 6626 if (TSI) { 6627 SDValue Result = TSI->EmitTargetCodeForMemset( 6628 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6629 if (Result.getNode()) 6630 return Result; 6631 } 6632 6633 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6634 6635 // Emit a library call. 6636 TargetLowering::ArgListTy Args; 6637 TargetLowering::ArgListEntry Entry; 6638 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6639 Args.push_back(Entry); 6640 Entry.Node = Src; 6641 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6642 Args.push_back(Entry); 6643 Entry.Node = Size; 6644 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6645 Args.push_back(Entry); 6646 6647 // FIXME: pass in SDLoc 6648 TargetLowering::CallLoweringInfo CLI(*this); 6649 CLI.setDebugLoc(dl) 6650 .setChain(Chain) 6651 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6652 Dst.getValueType().getTypeForEVT(*getContext()), 6653 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6654 TLI->getPointerTy(getDataLayout())), 6655 std::move(Args)) 6656 .setDiscardResult() 6657 .setTailCall(isTailCall); 6658 6659 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6660 return CallResult.second; 6661 } 6662 6663 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6664 SDValue Dst, unsigned DstAlign, 6665 SDValue Value, SDValue Size, Type *SizeTy, 6666 unsigned ElemSz, bool isTailCall, 6667 MachinePointerInfo DstPtrInfo) { 6668 // Emit a library call. 6669 TargetLowering::ArgListTy Args; 6670 TargetLowering::ArgListEntry Entry; 6671 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6672 Entry.Node = Dst; 6673 Args.push_back(Entry); 6674 6675 Entry.Ty = Type::getInt8Ty(*getContext()); 6676 Entry.Node = Value; 6677 Args.push_back(Entry); 6678 6679 Entry.Ty = SizeTy; 6680 Entry.Node = Size; 6681 Args.push_back(Entry); 6682 6683 RTLIB::Libcall LibraryCall = 6684 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6685 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6686 report_fatal_error("Unsupported element size"); 6687 6688 TargetLowering::CallLoweringInfo CLI(*this); 6689 CLI.setDebugLoc(dl) 6690 .setChain(Chain) 6691 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6692 Type::getVoidTy(*getContext()), 6693 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6694 TLI->getPointerTy(getDataLayout())), 6695 std::move(Args)) 6696 .setDiscardResult() 6697 .setTailCall(isTailCall); 6698 6699 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6700 return CallResult.second; 6701 } 6702 6703 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6704 SDVTList VTList, ArrayRef<SDValue> Ops, 6705 MachineMemOperand *MMO) { 6706 FoldingSetNodeID ID; 6707 ID.AddInteger(MemVT.getRawBits()); 6708 AddNodeIDNode(ID, Opcode, VTList, Ops); 6709 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6710 void* IP = nullptr; 6711 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6712 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6713 return SDValue(E, 0); 6714 } 6715 6716 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6717 VTList, MemVT, MMO); 6718 createOperands(N, Ops); 6719 6720 CSEMap.InsertNode(N, IP); 6721 InsertNode(N); 6722 return SDValue(N, 0); 6723 } 6724 6725 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6726 EVT MemVT, SDVTList VTs, SDValue Chain, 6727 SDValue Ptr, SDValue Cmp, SDValue Swp, 6728 MachineMemOperand *MMO) { 6729 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6730 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6731 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6732 6733 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6734 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6735 } 6736 6737 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6738 SDValue Chain, SDValue Ptr, SDValue Val, 6739 MachineMemOperand *MMO) { 6740 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6741 Opcode == ISD::ATOMIC_LOAD_SUB || 6742 Opcode == ISD::ATOMIC_LOAD_AND || 6743 Opcode == ISD::ATOMIC_LOAD_CLR || 6744 Opcode == ISD::ATOMIC_LOAD_OR || 6745 Opcode == ISD::ATOMIC_LOAD_XOR || 6746 Opcode == ISD::ATOMIC_LOAD_NAND || 6747 Opcode == ISD::ATOMIC_LOAD_MIN || 6748 Opcode == ISD::ATOMIC_LOAD_MAX || 6749 Opcode == ISD::ATOMIC_LOAD_UMIN || 6750 Opcode == ISD::ATOMIC_LOAD_UMAX || 6751 Opcode == ISD::ATOMIC_LOAD_FADD || 6752 Opcode == ISD::ATOMIC_LOAD_FSUB || 6753 Opcode == ISD::ATOMIC_SWAP || 6754 Opcode == ISD::ATOMIC_STORE) && 6755 "Invalid Atomic Op"); 6756 6757 EVT VT = Val.getValueType(); 6758 6759 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6760 getVTList(VT, MVT::Other); 6761 SDValue Ops[] = {Chain, Ptr, Val}; 6762 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6763 } 6764 6765 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6766 EVT VT, SDValue Chain, SDValue Ptr, 6767 MachineMemOperand *MMO) { 6768 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6769 6770 SDVTList VTs = getVTList(VT, MVT::Other); 6771 SDValue Ops[] = {Chain, Ptr}; 6772 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6773 } 6774 6775 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6776 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6777 if (Ops.size() == 1) 6778 return Ops[0]; 6779 6780 SmallVector<EVT, 4> VTs; 6781 VTs.reserve(Ops.size()); 6782 for (unsigned i = 0; i < Ops.size(); ++i) 6783 VTs.push_back(Ops[i].getValueType()); 6784 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6785 } 6786 6787 SDValue SelectionDAG::getMemIntrinsicNode( 6788 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6789 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 6790 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 6791 if (!Size && MemVT.isScalableVector()) 6792 Size = MemoryLocation::UnknownSize; 6793 else if (!Size) 6794 Size = MemVT.getStoreSize(); 6795 6796 MachineFunction &MF = getMachineFunction(); 6797 MachineMemOperand *MMO = 6798 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 6799 6800 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 6801 } 6802 6803 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 6804 SDVTList VTList, 6805 ArrayRef<SDValue> Ops, EVT MemVT, 6806 MachineMemOperand *MMO) { 6807 assert((Opcode == ISD::INTRINSIC_VOID || 6808 Opcode == ISD::INTRINSIC_W_CHAIN || 6809 Opcode == ISD::PREFETCH || 6810 ((int)Opcode <= std::numeric_limits<int>::max() && 6811 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 6812 "Opcode is not a memory-accessing opcode!"); 6813 6814 // Memoize the node unless it returns a flag. 6815 MemIntrinsicSDNode *N; 6816 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 6817 FoldingSetNodeID ID; 6818 AddNodeIDNode(ID, Opcode, VTList, Ops); 6819 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 6820 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 6821 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6822 void *IP = nullptr; 6823 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6824 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 6825 return SDValue(E, 0); 6826 } 6827 6828 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6829 VTList, MemVT, MMO); 6830 createOperands(N, Ops); 6831 6832 CSEMap.InsertNode(N, IP); 6833 } else { 6834 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6835 VTList, MemVT, MMO); 6836 createOperands(N, Ops); 6837 } 6838 InsertNode(N); 6839 SDValue V(N, 0); 6840 NewSDValueDbgMsg(V, "Creating new node: ", this); 6841 return V; 6842 } 6843 6844 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 6845 SDValue Chain, int FrameIndex, 6846 int64_t Size, int64_t Offset) { 6847 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 6848 const auto VTs = getVTList(MVT::Other); 6849 SDValue Ops[2] = { 6850 Chain, 6851 getFrameIndex(FrameIndex, 6852 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 6853 true)}; 6854 6855 FoldingSetNodeID ID; 6856 AddNodeIDNode(ID, Opcode, VTs, Ops); 6857 ID.AddInteger(FrameIndex); 6858 ID.AddInteger(Size); 6859 ID.AddInteger(Offset); 6860 void *IP = nullptr; 6861 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6862 return SDValue(E, 0); 6863 6864 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 6865 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 6866 createOperands(N, Ops); 6867 CSEMap.InsertNode(N, IP); 6868 InsertNode(N); 6869 SDValue V(N, 0); 6870 NewSDValueDbgMsg(V, "Creating new node: ", this); 6871 return V; 6872 } 6873 6874 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 6875 uint64_t Guid, uint64_t Index, 6876 uint32_t Attr) { 6877 const unsigned Opcode = ISD::PSEUDO_PROBE; 6878 const auto VTs = getVTList(MVT::Other); 6879 SDValue Ops[] = {Chain}; 6880 FoldingSetNodeID ID; 6881 AddNodeIDNode(ID, Opcode, VTs, Ops); 6882 ID.AddInteger(Guid); 6883 ID.AddInteger(Index); 6884 void *IP = nullptr; 6885 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 6886 return SDValue(E, 0); 6887 6888 auto *N = newSDNode<PseudoProbeSDNode>( 6889 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 6890 createOperands(N, Ops); 6891 CSEMap.InsertNode(N, IP); 6892 InsertNode(N); 6893 SDValue V(N, 0); 6894 NewSDValueDbgMsg(V, "Creating new node: ", this); 6895 return V; 6896 } 6897 6898 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6899 /// MachinePointerInfo record from it. This is particularly useful because the 6900 /// code generator has many cases where it doesn't bother passing in a 6901 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6902 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6903 SelectionDAG &DAG, SDValue Ptr, 6904 int64_t Offset = 0) { 6905 // If this is FI+Offset, we can model it. 6906 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 6907 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 6908 FI->getIndex(), Offset); 6909 6910 // If this is (FI+Offset1)+Offset2, we can model it. 6911 if (Ptr.getOpcode() != ISD::ADD || 6912 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 6913 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 6914 return Info; 6915 6916 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 6917 return MachinePointerInfo::getFixedStack( 6918 DAG.getMachineFunction(), FI, 6919 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 6920 } 6921 6922 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6923 /// MachinePointerInfo record from it. This is particularly useful because the 6924 /// code generator has many cases where it doesn't bother passing in a 6925 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6926 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6927 SelectionDAG &DAG, SDValue Ptr, 6928 SDValue OffsetOp) { 6929 // If the 'Offset' value isn't a constant, we can't handle this. 6930 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 6931 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 6932 if (OffsetOp.isUndef()) 6933 return InferPointerInfo(Info, DAG, Ptr); 6934 return Info; 6935 } 6936 6937 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6938 EVT VT, const SDLoc &dl, SDValue Chain, 6939 SDValue Ptr, SDValue Offset, 6940 MachinePointerInfo PtrInfo, EVT MemVT, 6941 Align Alignment, 6942 MachineMemOperand::Flags MMOFlags, 6943 const AAMDNodes &AAInfo, const MDNode *Ranges) { 6944 assert(Chain.getValueType() == MVT::Other && 6945 "Invalid chain type"); 6946 6947 MMOFlags |= MachineMemOperand::MOLoad; 6948 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 6949 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 6950 // clients. 6951 if (PtrInfo.V.isNull()) 6952 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 6953 6954 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 6955 MachineFunction &MF = getMachineFunction(); 6956 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 6957 Alignment, AAInfo, Ranges); 6958 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 6959 } 6960 6961 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6962 EVT VT, const SDLoc &dl, SDValue Chain, 6963 SDValue Ptr, SDValue Offset, EVT MemVT, 6964 MachineMemOperand *MMO) { 6965 if (VT == MemVT) { 6966 ExtType = ISD::NON_EXTLOAD; 6967 } else if (ExtType == ISD::NON_EXTLOAD) { 6968 assert(VT == MemVT && "Non-extending load from different memory type!"); 6969 } else { 6970 // Extending load. 6971 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 6972 "Should only be an extending load, not truncating!"); 6973 assert(VT.isInteger() == MemVT.isInteger() && 6974 "Cannot convert from FP to Int or Int -> FP!"); 6975 assert(VT.isVector() == MemVT.isVector() && 6976 "Cannot use an ext load to convert to or from a vector!"); 6977 assert((!VT.isVector() || 6978 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 6979 "Cannot use an ext load to change the number of vector elements!"); 6980 } 6981 6982 bool Indexed = AM != ISD::UNINDEXED; 6983 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 6984 6985 SDVTList VTs = Indexed ? 6986 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 6987 SDValue Ops[] = { Chain, Ptr, Offset }; 6988 FoldingSetNodeID ID; 6989 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 6990 ID.AddInteger(MemVT.getRawBits()); 6991 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 6992 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 6993 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6994 void *IP = nullptr; 6995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6996 cast<LoadSDNode>(E)->refineAlignment(MMO); 6997 return SDValue(E, 0); 6998 } 6999 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7000 ExtType, MemVT, MMO); 7001 createOperands(N, Ops); 7002 7003 CSEMap.InsertNode(N, IP); 7004 InsertNode(N); 7005 SDValue V(N, 0); 7006 NewSDValueDbgMsg(V, "Creating new node: ", this); 7007 return V; 7008 } 7009 7010 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7011 SDValue Ptr, MachinePointerInfo PtrInfo, 7012 MaybeAlign Alignment, 7013 MachineMemOperand::Flags MMOFlags, 7014 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7015 SDValue Undef = getUNDEF(Ptr.getValueType()); 7016 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7017 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7018 } 7019 7020 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7021 SDValue Ptr, MachineMemOperand *MMO) { 7022 SDValue Undef = getUNDEF(Ptr.getValueType()); 7023 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7024 VT, MMO); 7025 } 7026 7027 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7028 EVT VT, SDValue Chain, SDValue Ptr, 7029 MachinePointerInfo PtrInfo, EVT MemVT, 7030 MaybeAlign Alignment, 7031 MachineMemOperand::Flags MMOFlags, 7032 const AAMDNodes &AAInfo) { 7033 SDValue Undef = getUNDEF(Ptr.getValueType()); 7034 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7035 MemVT, Alignment, MMOFlags, AAInfo); 7036 } 7037 7038 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7039 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7040 MachineMemOperand *MMO) { 7041 SDValue Undef = getUNDEF(Ptr.getValueType()); 7042 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7043 MemVT, MMO); 7044 } 7045 7046 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7047 SDValue Base, SDValue Offset, 7048 ISD::MemIndexedMode AM) { 7049 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7050 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7051 // Don't propagate the invariant or dereferenceable flags. 7052 auto MMOFlags = 7053 LD->getMemOperand()->getFlags() & 7054 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7055 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7056 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7057 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7058 } 7059 7060 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7061 SDValue Ptr, MachinePointerInfo PtrInfo, 7062 Align Alignment, 7063 MachineMemOperand::Flags MMOFlags, 7064 const AAMDNodes &AAInfo) { 7065 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7066 7067 MMOFlags |= MachineMemOperand::MOStore; 7068 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7069 7070 if (PtrInfo.V.isNull()) 7071 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7072 7073 MachineFunction &MF = getMachineFunction(); 7074 uint64_t Size = 7075 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7076 MachineMemOperand *MMO = 7077 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7078 return getStore(Chain, dl, Val, Ptr, MMO); 7079 } 7080 7081 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7082 SDValue Ptr, MachineMemOperand *MMO) { 7083 assert(Chain.getValueType() == MVT::Other && 7084 "Invalid chain type"); 7085 EVT VT = Val.getValueType(); 7086 SDVTList VTs = getVTList(MVT::Other); 7087 SDValue Undef = getUNDEF(Ptr.getValueType()); 7088 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7089 FoldingSetNodeID ID; 7090 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7091 ID.AddInteger(VT.getRawBits()); 7092 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7093 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7094 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7095 void *IP = nullptr; 7096 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7097 cast<StoreSDNode>(E)->refineAlignment(MMO); 7098 return SDValue(E, 0); 7099 } 7100 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7101 ISD::UNINDEXED, false, VT, MMO); 7102 createOperands(N, Ops); 7103 7104 CSEMap.InsertNode(N, IP); 7105 InsertNode(N); 7106 SDValue V(N, 0); 7107 NewSDValueDbgMsg(V, "Creating new node: ", this); 7108 return V; 7109 } 7110 7111 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7112 SDValue Ptr, MachinePointerInfo PtrInfo, 7113 EVT SVT, Align Alignment, 7114 MachineMemOperand::Flags MMOFlags, 7115 const AAMDNodes &AAInfo) { 7116 assert(Chain.getValueType() == MVT::Other && 7117 "Invalid chain type"); 7118 7119 MMOFlags |= MachineMemOperand::MOStore; 7120 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7121 7122 if (PtrInfo.V.isNull()) 7123 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7124 7125 MachineFunction &MF = getMachineFunction(); 7126 MachineMemOperand *MMO = MF.getMachineMemOperand( 7127 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7128 Alignment, AAInfo); 7129 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7130 } 7131 7132 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7133 SDValue Ptr, EVT SVT, 7134 MachineMemOperand *MMO) { 7135 EVT VT = Val.getValueType(); 7136 7137 assert(Chain.getValueType() == MVT::Other && 7138 "Invalid chain type"); 7139 if (VT == SVT) 7140 return getStore(Chain, dl, Val, Ptr, MMO); 7141 7142 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7143 "Should only be a truncating store, not extending!"); 7144 assert(VT.isInteger() == SVT.isInteger() && 7145 "Can't do FP-INT conversion!"); 7146 assert(VT.isVector() == SVT.isVector() && 7147 "Cannot use trunc store to convert to or from a vector!"); 7148 assert((!VT.isVector() || 7149 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7150 "Cannot use trunc store to change the number of vector elements!"); 7151 7152 SDVTList VTs = getVTList(MVT::Other); 7153 SDValue Undef = getUNDEF(Ptr.getValueType()); 7154 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7155 FoldingSetNodeID ID; 7156 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7157 ID.AddInteger(SVT.getRawBits()); 7158 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7159 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7160 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7161 void *IP = nullptr; 7162 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7163 cast<StoreSDNode>(E)->refineAlignment(MMO); 7164 return SDValue(E, 0); 7165 } 7166 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7167 ISD::UNINDEXED, true, SVT, MMO); 7168 createOperands(N, Ops); 7169 7170 CSEMap.InsertNode(N, IP); 7171 InsertNode(N); 7172 SDValue V(N, 0); 7173 NewSDValueDbgMsg(V, "Creating new node: ", this); 7174 return V; 7175 } 7176 7177 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7178 SDValue Base, SDValue Offset, 7179 ISD::MemIndexedMode AM) { 7180 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7181 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7182 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7183 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7184 FoldingSetNodeID ID; 7185 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7186 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7187 ID.AddInteger(ST->getRawSubclassData()); 7188 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7189 void *IP = nullptr; 7190 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7191 return SDValue(E, 0); 7192 7193 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7194 ST->isTruncatingStore(), ST->getMemoryVT(), 7195 ST->getMemOperand()); 7196 createOperands(N, Ops); 7197 7198 CSEMap.InsertNode(N, IP); 7199 InsertNode(N); 7200 SDValue V(N, 0); 7201 NewSDValueDbgMsg(V, "Creating new node: ", this); 7202 return V; 7203 } 7204 7205 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7206 SDValue Base, SDValue Offset, SDValue Mask, 7207 SDValue PassThru, EVT MemVT, 7208 MachineMemOperand *MMO, 7209 ISD::MemIndexedMode AM, 7210 ISD::LoadExtType ExtTy, bool isExpanding) { 7211 bool Indexed = AM != ISD::UNINDEXED; 7212 assert((Indexed || Offset.isUndef()) && 7213 "Unindexed masked load with an offset!"); 7214 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7215 : getVTList(VT, MVT::Other); 7216 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7217 FoldingSetNodeID ID; 7218 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7219 ID.AddInteger(MemVT.getRawBits()); 7220 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7221 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7222 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7223 void *IP = nullptr; 7224 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7225 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7226 return SDValue(E, 0); 7227 } 7228 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7229 AM, ExtTy, isExpanding, MemVT, MMO); 7230 createOperands(N, Ops); 7231 7232 CSEMap.InsertNode(N, IP); 7233 InsertNode(N); 7234 SDValue V(N, 0); 7235 NewSDValueDbgMsg(V, "Creating new node: ", this); 7236 return V; 7237 } 7238 7239 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7240 SDValue Base, SDValue Offset, 7241 ISD::MemIndexedMode AM) { 7242 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7243 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7244 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7245 Offset, LD->getMask(), LD->getPassThru(), 7246 LD->getMemoryVT(), LD->getMemOperand(), AM, 7247 LD->getExtensionType(), LD->isExpandingLoad()); 7248 } 7249 7250 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7251 SDValue Val, SDValue Base, SDValue Offset, 7252 SDValue Mask, EVT MemVT, 7253 MachineMemOperand *MMO, 7254 ISD::MemIndexedMode AM, bool IsTruncating, 7255 bool IsCompressing) { 7256 assert(Chain.getValueType() == MVT::Other && 7257 "Invalid chain type"); 7258 bool Indexed = AM != ISD::UNINDEXED; 7259 assert((Indexed || Offset.isUndef()) && 7260 "Unindexed masked store with an offset!"); 7261 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7262 : getVTList(MVT::Other); 7263 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7264 FoldingSetNodeID ID; 7265 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7266 ID.AddInteger(MemVT.getRawBits()); 7267 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7268 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7269 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7270 void *IP = nullptr; 7271 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7272 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7273 return SDValue(E, 0); 7274 } 7275 auto *N = 7276 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7277 IsTruncating, IsCompressing, MemVT, MMO); 7278 createOperands(N, Ops); 7279 7280 CSEMap.InsertNode(N, IP); 7281 InsertNode(N); 7282 SDValue V(N, 0); 7283 NewSDValueDbgMsg(V, "Creating new node: ", this); 7284 return V; 7285 } 7286 7287 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7288 SDValue Base, SDValue Offset, 7289 ISD::MemIndexedMode AM) { 7290 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7291 assert(ST->getOffset().isUndef() && 7292 "Masked store is already a indexed store!"); 7293 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7294 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7295 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7296 } 7297 7298 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7299 ArrayRef<SDValue> Ops, 7300 MachineMemOperand *MMO, 7301 ISD::MemIndexType IndexType, 7302 ISD::LoadExtType ExtTy) { 7303 assert(Ops.size() == 6 && "Incompatible number of operands"); 7304 7305 FoldingSetNodeID ID; 7306 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7307 ID.AddInteger(VT.getRawBits()); 7308 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7309 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7310 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7311 void *IP = nullptr; 7312 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7313 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7314 return SDValue(E, 0); 7315 } 7316 7317 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7318 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7319 VTs, VT, MMO, IndexType, ExtTy); 7320 createOperands(N, Ops); 7321 7322 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7323 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7324 assert(N->getMask().getValueType().getVectorElementCount() == 7325 N->getValueType(0).getVectorElementCount() && 7326 "Vector width mismatch between mask and data"); 7327 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7328 N->getValueType(0).getVectorElementCount().isScalable() && 7329 "Scalable flags of index and data do not match"); 7330 assert(ElementCount::isKnownGE( 7331 N->getIndex().getValueType().getVectorElementCount(), 7332 N->getValueType(0).getVectorElementCount()) && 7333 "Vector width mismatch between index and data"); 7334 assert(isa<ConstantSDNode>(N->getScale()) && 7335 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7336 "Scale should be a constant power of 2"); 7337 7338 CSEMap.InsertNode(N, IP); 7339 InsertNode(N); 7340 SDValue V(N, 0); 7341 NewSDValueDbgMsg(V, "Creating new node: ", this); 7342 return V; 7343 } 7344 7345 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7346 ArrayRef<SDValue> Ops, 7347 MachineMemOperand *MMO, 7348 ISD::MemIndexType IndexType, 7349 bool IsTrunc) { 7350 assert(Ops.size() == 6 && "Incompatible number of operands"); 7351 7352 FoldingSetNodeID ID; 7353 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7354 ID.AddInteger(VT.getRawBits()); 7355 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7356 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7357 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7358 void *IP = nullptr; 7359 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7360 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7361 return SDValue(E, 0); 7362 } 7363 7364 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7365 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7366 VTs, VT, MMO, IndexType, IsTrunc); 7367 createOperands(N, Ops); 7368 7369 assert(N->getMask().getValueType().getVectorElementCount() == 7370 N->getValue().getValueType().getVectorElementCount() && 7371 "Vector width mismatch between mask and data"); 7372 assert( 7373 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7374 N->getValue().getValueType().getVectorElementCount().isScalable() && 7375 "Scalable flags of index and data do not match"); 7376 assert(ElementCount::isKnownGE( 7377 N->getIndex().getValueType().getVectorElementCount(), 7378 N->getValue().getValueType().getVectorElementCount()) && 7379 "Vector width mismatch between index and data"); 7380 assert(isa<ConstantSDNode>(N->getScale()) && 7381 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7382 "Scale should be a constant power of 2"); 7383 7384 CSEMap.InsertNode(N, IP); 7385 InsertNode(N); 7386 SDValue V(N, 0); 7387 NewSDValueDbgMsg(V, "Creating new node: ", this); 7388 return V; 7389 } 7390 7391 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7392 // select undef, T, F --> T (if T is a constant), otherwise F 7393 // select, ?, undef, F --> F 7394 // select, ?, T, undef --> T 7395 if (Cond.isUndef()) 7396 return isConstantValueOfAnyType(T) ? T : F; 7397 if (T.isUndef()) 7398 return F; 7399 if (F.isUndef()) 7400 return T; 7401 7402 // select true, T, F --> T 7403 // select false, T, F --> F 7404 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7405 return CondC->isNullValue() ? F : T; 7406 7407 // TODO: This should simplify VSELECT with constant condition using something 7408 // like this (but check boolean contents to be complete?): 7409 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7410 // return T; 7411 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7412 // return F; 7413 7414 // select ?, T, T --> T 7415 if (T == F) 7416 return T; 7417 7418 return SDValue(); 7419 } 7420 7421 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7422 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7423 if (X.isUndef()) 7424 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7425 // shift X, undef --> undef (because it may shift by the bitwidth) 7426 if (Y.isUndef()) 7427 return getUNDEF(X.getValueType()); 7428 7429 // shift 0, Y --> 0 7430 // shift X, 0 --> X 7431 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7432 return X; 7433 7434 // shift X, C >= bitwidth(X) --> undef 7435 // All vector elements must be too big (or undef) to avoid partial undefs. 7436 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7437 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7438 }; 7439 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7440 return getUNDEF(X.getValueType()); 7441 7442 return SDValue(); 7443 } 7444 7445 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7446 SDNodeFlags Flags) { 7447 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7448 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7449 // operation is poison. That result can be relaxed to undef. 7450 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7451 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7452 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7453 (YC && YC->getValueAPF().isNaN()); 7454 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7455 (YC && YC->getValueAPF().isInfinity()); 7456 7457 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7458 return getUNDEF(X.getValueType()); 7459 7460 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7461 return getUNDEF(X.getValueType()); 7462 7463 if (!YC) 7464 return SDValue(); 7465 7466 // X + -0.0 --> X 7467 if (Opcode == ISD::FADD) 7468 if (YC->getValueAPF().isNegZero()) 7469 return X; 7470 7471 // X - +0.0 --> X 7472 if (Opcode == ISD::FSUB) 7473 if (YC->getValueAPF().isPosZero()) 7474 return X; 7475 7476 // X * 1.0 --> X 7477 // X / 1.0 --> X 7478 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7479 if (YC->getValueAPF().isExactlyValue(1.0)) 7480 return X; 7481 7482 // X * 0.0 --> 0.0 7483 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7484 if (YC->getValueAPF().isZero()) 7485 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7486 7487 return SDValue(); 7488 } 7489 7490 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7491 SDValue Ptr, SDValue SV, unsigned Align) { 7492 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7493 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7494 } 7495 7496 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7497 ArrayRef<SDUse> Ops) { 7498 switch (Ops.size()) { 7499 case 0: return getNode(Opcode, DL, VT); 7500 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7501 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7502 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7503 default: break; 7504 } 7505 7506 // Copy from an SDUse array into an SDValue array for use with 7507 // the regular getNode logic. 7508 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7509 return getNode(Opcode, DL, VT, NewOps); 7510 } 7511 7512 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7513 ArrayRef<SDValue> Ops) { 7514 SDNodeFlags Flags; 7515 if (Inserter) 7516 Flags = Inserter->getFlags(); 7517 return getNode(Opcode, DL, VT, Ops, Flags); 7518 } 7519 7520 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7521 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7522 unsigned NumOps = Ops.size(); 7523 switch (NumOps) { 7524 case 0: return getNode(Opcode, DL, VT); 7525 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7526 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7527 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7528 default: break; 7529 } 7530 7531 switch (Opcode) { 7532 default: break; 7533 case ISD::BUILD_VECTOR: 7534 // Attempt to simplify BUILD_VECTOR. 7535 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7536 return V; 7537 break; 7538 case ISD::CONCAT_VECTORS: 7539 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7540 return V; 7541 break; 7542 case ISD::SELECT_CC: 7543 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7544 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7545 "LHS and RHS of condition must have same type!"); 7546 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7547 "True and False arms of SelectCC must have same type!"); 7548 assert(Ops[2].getValueType() == VT && 7549 "select_cc node must be of same type as true and false value!"); 7550 break; 7551 case ISD::BR_CC: 7552 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7553 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7554 "LHS/RHS of comparison should match types!"); 7555 break; 7556 } 7557 7558 // Memoize nodes. 7559 SDNode *N; 7560 SDVTList VTs = getVTList(VT); 7561 7562 if (VT != MVT::Glue) { 7563 FoldingSetNodeID ID; 7564 AddNodeIDNode(ID, Opcode, VTs, Ops); 7565 void *IP = nullptr; 7566 7567 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7568 return SDValue(E, 0); 7569 7570 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7571 createOperands(N, Ops); 7572 7573 CSEMap.InsertNode(N, IP); 7574 } else { 7575 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7576 createOperands(N, Ops); 7577 } 7578 7579 N->setFlags(Flags); 7580 InsertNode(N); 7581 SDValue V(N, 0); 7582 NewSDValueDbgMsg(V, "Creating new node: ", this); 7583 return V; 7584 } 7585 7586 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7587 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7588 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7589 } 7590 7591 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7592 ArrayRef<SDValue> Ops) { 7593 SDNodeFlags Flags; 7594 if (Inserter) 7595 Flags = Inserter->getFlags(); 7596 return getNode(Opcode, DL, VTList, Ops, Flags); 7597 } 7598 7599 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7600 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7601 if (VTList.NumVTs == 1) 7602 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7603 7604 switch (Opcode) { 7605 case ISD::STRICT_FP_EXTEND: 7606 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7607 "Invalid STRICT_FP_EXTEND!"); 7608 assert(VTList.VTs[0].isFloatingPoint() && 7609 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7610 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7611 "STRICT_FP_EXTEND result type should be vector iff the operand " 7612 "type is vector!"); 7613 assert((!VTList.VTs[0].isVector() || 7614 VTList.VTs[0].getVectorNumElements() == 7615 Ops[1].getValueType().getVectorNumElements()) && 7616 "Vector element count mismatch!"); 7617 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7618 "Invalid fpext node, dst <= src!"); 7619 break; 7620 case ISD::STRICT_FP_ROUND: 7621 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7622 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7623 "STRICT_FP_ROUND result type should be vector iff the operand " 7624 "type is vector!"); 7625 assert((!VTList.VTs[0].isVector() || 7626 VTList.VTs[0].getVectorNumElements() == 7627 Ops[1].getValueType().getVectorNumElements()) && 7628 "Vector element count mismatch!"); 7629 assert(VTList.VTs[0].isFloatingPoint() && 7630 Ops[1].getValueType().isFloatingPoint() && 7631 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7632 isa<ConstantSDNode>(Ops[2]) && 7633 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7634 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7635 "Invalid STRICT_FP_ROUND!"); 7636 break; 7637 #if 0 7638 // FIXME: figure out how to safely handle things like 7639 // int foo(int x) { return 1 << (x & 255); } 7640 // int bar() { return foo(256); } 7641 case ISD::SRA_PARTS: 7642 case ISD::SRL_PARTS: 7643 case ISD::SHL_PARTS: 7644 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7645 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7646 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7647 else if (N3.getOpcode() == ISD::AND) 7648 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7649 // If the and is only masking out bits that cannot effect the shift, 7650 // eliminate the and. 7651 unsigned NumBits = VT.getScalarSizeInBits()*2; 7652 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7653 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7654 } 7655 break; 7656 #endif 7657 } 7658 7659 // Memoize the node unless it returns a flag. 7660 SDNode *N; 7661 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7662 FoldingSetNodeID ID; 7663 AddNodeIDNode(ID, Opcode, VTList, Ops); 7664 void *IP = nullptr; 7665 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7666 return SDValue(E, 0); 7667 7668 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7669 createOperands(N, Ops); 7670 CSEMap.InsertNode(N, IP); 7671 } else { 7672 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7673 createOperands(N, Ops); 7674 } 7675 7676 N->setFlags(Flags); 7677 InsertNode(N); 7678 SDValue V(N, 0); 7679 NewSDValueDbgMsg(V, "Creating new node: ", this); 7680 return V; 7681 } 7682 7683 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7684 SDVTList VTList) { 7685 return getNode(Opcode, DL, VTList, None); 7686 } 7687 7688 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7689 SDValue N1) { 7690 SDValue Ops[] = { N1 }; 7691 return getNode(Opcode, DL, VTList, Ops); 7692 } 7693 7694 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7695 SDValue N1, SDValue N2) { 7696 SDValue Ops[] = { N1, N2 }; 7697 return getNode(Opcode, DL, VTList, Ops); 7698 } 7699 7700 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7701 SDValue N1, SDValue N2, SDValue N3) { 7702 SDValue Ops[] = { N1, N2, N3 }; 7703 return getNode(Opcode, DL, VTList, Ops); 7704 } 7705 7706 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7707 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7708 SDValue Ops[] = { N1, N2, N3, N4 }; 7709 return getNode(Opcode, DL, VTList, Ops); 7710 } 7711 7712 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7713 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7714 SDValue N5) { 7715 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7716 return getNode(Opcode, DL, VTList, Ops); 7717 } 7718 7719 SDVTList SelectionDAG::getVTList(EVT VT) { 7720 return makeVTList(SDNode::getValueTypeList(VT), 1); 7721 } 7722 7723 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7724 FoldingSetNodeID ID; 7725 ID.AddInteger(2U); 7726 ID.AddInteger(VT1.getRawBits()); 7727 ID.AddInteger(VT2.getRawBits()); 7728 7729 void *IP = nullptr; 7730 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7731 if (!Result) { 7732 EVT *Array = Allocator.Allocate<EVT>(2); 7733 Array[0] = VT1; 7734 Array[1] = VT2; 7735 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7736 VTListMap.InsertNode(Result, IP); 7737 } 7738 return Result->getSDVTList(); 7739 } 7740 7741 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7742 FoldingSetNodeID ID; 7743 ID.AddInteger(3U); 7744 ID.AddInteger(VT1.getRawBits()); 7745 ID.AddInteger(VT2.getRawBits()); 7746 ID.AddInteger(VT3.getRawBits()); 7747 7748 void *IP = nullptr; 7749 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7750 if (!Result) { 7751 EVT *Array = Allocator.Allocate<EVT>(3); 7752 Array[0] = VT1; 7753 Array[1] = VT2; 7754 Array[2] = VT3; 7755 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7756 VTListMap.InsertNode(Result, IP); 7757 } 7758 return Result->getSDVTList(); 7759 } 7760 7761 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7762 FoldingSetNodeID ID; 7763 ID.AddInteger(4U); 7764 ID.AddInteger(VT1.getRawBits()); 7765 ID.AddInteger(VT2.getRawBits()); 7766 ID.AddInteger(VT3.getRawBits()); 7767 ID.AddInteger(VT4.getRawBits()); 7768 7769 void *IP = nullptr; 7770 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7771 if (!Result) { 7772 EVT *Array = Allocator.Allocate<EVT>(4); 7773 Array[0] = VT1; 7774 Array[1] = VT2; 7775 Array[2] = VT3; 7776 Array[3] = VT4; 7777 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7778 VTListMap.InsertNode(Result, IP); 7779 } 7780 return Result->getSDVTList(); 7781 } 7782 7783 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7784 unsigned NumVTs = VTs.size(); 7785 FoldingSetNodeID ID; 7786 ID.AddInteger(NumVTs); 7787 for (unsigned index = 0; index < NumVTs; index++) { 7788 ID.AddInteger(VTs[index].getRawBits()); 7789 } 7790 7791 void *IP = nullptr; 7792 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7793 if (!Result) { 7794 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 7795 llvm::copy(VTs, Array); 7796 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 7797 VTListMap.InsertNode(Result, IP); 7798 } 7799 return Result->getSDVTList(); 7800 } 7801 7802 7803 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 7804 /// specified operands. If the resultant node already exists in the DAG, 7805 /// this does not modify the specified node, instead it returns the node that 7806 /// already exists. If the resultant node does not exist in the DAG, the 7807 /// input node is returned. As a degenerate case, if you specify the same 7808 /// input operands as the node already has, the input node is returned. 7809 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 7810 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 7811 7812 // Check to see if there is no change. 7813 if (Op == N->getOperand(0)) return N; 7814 7815 // See if the modified node already exists. 7816 void *InsertPos = nullptr; 7817 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 7818 return Existing; 7819 7820 // Nope it doesn't. Remove the node from its current place in the maps. 7821 if (InsertPos) 7822 if (!RemoveNodeFromCSEMaps(N)) 7823 InsertPos = nullptr; 7824 7825 // Now we update the operands. 7826 N->OperandList[0].set(Op); 7827 7828 updateDivergence(N); 7829 // If this gets put into a CSE map, add it. 7830 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7831 return N; 7832 } 7833 7834 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 7835 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 7836 7837 // Check to see if there is no change. 7838 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 7839 return N; // No operands changed, just return the input node. 7840 7841 // See if the modified node already exists. 7842 void *InsertPos = nullptr; 7843 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 7844 return Existing; 7845 7846 // Nope it doesn't. Remove the node from its current place in the maps. 7847 if (InsertPos) 7848 if (!RemoveNodeFromCSEMaps(N)) 7849 InsertPos = nullptr; 7850 7851 // Now we update the operands. 7852 if (N->OperandList[0] != Op1) 7853 N->OperandList[0].set(Op1); 7854 if (N->OperandList[1] != Op2) 7855 N->OperandList[1].set(Op2); 7856 7857 updateDivergence(N); 7858 // If this gets put into a CSE map, add it. 7859 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7860 return N; 7861 } 7862 7863 SDNode *SelectionDAG:: 7864 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 7865 SDValue Ops[] = { Op1, Op2, Op3 }; 7866 return UpdateNodeOperands(N, Ops); 7867 } 7868 7869 SDNode *SelectionDAG:: 7870 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7871 SDValue Op3, SDValue Op4) { 7872 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 7873 return UpdateNodeOperands(N, Ops); 7874 } 7875 7876 SDNode *SelectionDAG:: 7877 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7878 SDValue Op3, SDValue Op4, SDValue Op5) { 7879 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 7880 return UpdateNodeOperands(N, Ops); 7881 } 7882 7883 SDNode *SelectionDAG:: 7884 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 7885 unsigned NumOps = Ops.size(); 7886 assert(N->getNumOperands() == NumOps && 7887 "Update with wrong number of operands"); 7888 7889 // If no operands changed just return the input node. 7890 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 7891 return N; 7892 7893 // See if the modified node already exists. 7894 void *InsertPos = nullptr; 7895 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 7896 return Existing; 7897 7898 // Nope it doesn't. Remove the node from its current place in the maps. 7899 if (InsertPos) 7900 if (!RemoveNodeFromCSEMaps(N)) 7901 InsertPos = nullptr; 7902 7903 // Now we update the operands. 7904 for (unsigned i = 0; i != NumOps; ++i) 7905 if (N->OperandList[i] != Ops[i]) 7906 N->OperandList[i].set(Ops[i]); 7907 7908 updateDivergence(N); 7909 // If this gets put into a CSE map, add it. 7910 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7911 return N; 7912 } 7913 7914 /// DropOperands - Release the operands and set this node to have 7915 /// zero operands. 7916 void SDNode::DropOperands() { 7917 // Unlike the code in MorphNodeTo that does this, we don't need to 7918 // watch for dead nodes here. 7919 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 7920 SDUse &Use = *I++; 7921 Use.set(SDValue()); 7922 } 7923 } 7924 7925 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 7926 ArrayRef<MachineMemOperand *> NewMemRefs) { 7927 if (NewMemRefs.empty()) { 7928 N->clearMemRefs(); 7929 return; 7930 } 7931 7932 // Check if we can avoid allocating by storing a single reference directly. 7933 if (NewMemRefs.size() == 1) { 7934 N->MemRefs = NewMemRefs[0]; 7935 N->NumMemRefs = 1; 7936 return; 7937 } 7938 7939 MachineMemOperand **MemRefsBuffer = 7940 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 7941 llvm::copy(NewMemRefs, MemRefsBuffer); 7942 N->MemRefs = MemRefsBuffer; 7943 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 7944 } 7945 7946 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 7947 /// machine opcode. 7948 /// 7949 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7950 EVT VT) { 7951 SDVTList VTs = getVTList(VT); 7952 return SelectNodeTo(N, MachineOpc, VTs, None); 7953 } 7954 7955 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7956 EVT VT, SDValue Op1) { 7957 SDVTList VTs = getVTList(VT); 7958 SDValue Ops[] = { Op1 }; 7959 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7960 } 7961 7962 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7963 EVT VT, SDValue Op1, 7964 SDValue Op2) { 7965 SDVTList VTs = getVTList(VT); 7966 SDValue Ops[] = { Op1, Op2 }; 7967 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7968 } 7969 7970 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7971 EVT VT, SDValue Op1, 7972 SDValue Op2, SDValue Op3) { 7973 SDVTList VTs = getVTList(VT); 7974 SDValue Ops[] = { Op1, Op2, Op3 }; 7975 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7976 } 7977 7978 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7979 EVT VT, ArrayRef<SDValue> Ops) { 7980 SDVTList VTs = getVTList(VT); 7981 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7982 } 7983 7984 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7985 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 7986 SDVTList VTs = getVTList(VT1, VT2); 7987 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7988 } 7989 7990 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7991 EVT VT1, EVT VT2) { 7992 SDVTList VTs = getVTList(VT1, VT2); 7993 return SelectNodeTo(N, MachineOpc, VTs, None); 7994 } 7995 7996 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7997 EVT VT1, EVT VT2, EVT VT3, 7998 ArrayRef<SDValue> Ops) { 7999 SDVTList VTs = getVTList(VT1, VT2, VT3); 8000 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8001 } 8002 8003 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8004 EVT VT1, EVT VT2, 8005 SDValue Op1, SDValue Op2) { 8006 SDVTList VTs = getVTList(VT1, VT2); 8007 SDValue Ops[] = { Op1, Op2 }; 8008 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8009 } 8010 8011 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8012 SDVTList VTs,ArrayRef<SDValue> Ops) { 8013 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8014 // Reset the NodeID to -1. 8015 New->setNodeId(-1); 8016 if (New != N) { 8017 ReplaceAllUsesWith(N, New); 8018 RemoveDeadNode(N); 8019 } 8020 return New; 8021 } 8022 8023 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8024 /// the line number information on the merged node since it is not possible to 8025 /// preserve the information that operation is associated with multiple lines. 8026 /// This will make the debugger working better at -O0, were there is a higher 8027 /// probability having other instructions associated with that line. 8028 /// 8029 /// For IROrder, we keep the smaller of the two 8030 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8031 DebugLoc NLoc = N->getDebugLoc(); 8032 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8033 N->setDebugLoc(DebugLoc()); 8034 } 8035 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8036 N->setIROrder(Order); 8037 return N; 8038 } 8039 8040 /// MorphNodeTo - This *mutates* the specified node to have the specified 8041 /// return type, opcode, and operands. 8042 /// 8043 /// Note that MorphNodeTo returns the resultant node. If there is already a 8044 /// node of the specified opcode and operands, it returns that node instead of 8045 /// the current one. Note that the SDLoc need not be the same. 8046 /// 8047 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8048 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8049 /// node, and because it doesn't require CSE recalculation for any of 8050 /// the node's users. 8051 /// 8052 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8053 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8054 /// the legalizer which maintain worklists that would need to be updated when 8055 /// deleting things. 8056 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8057 SDVTList VTs, ArrayRef<SDValue> Ops) { 8058 // If an identical node already exists, use it. 8059 void *IP = nullptr; 8060 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8061 FoldingSetNodeID ID; 8062 AddNodeIDNode(ID, Opc, VTs, Ops); 8063 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8064 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8065 } 8066 8067 if (!RemoveNodeFromCSEMaps(N)) 8068 IP = nullptr; 8069 8070 // Start the morphing. 8071 N->NodeType = Opc; 8072 N->ValueList = VTs.VTs; 8073 N->NumValues = VTs.NumVTs; 8074 8075 // Clear the operands list, updating used nodes to remove this from their 8076 // use list. Keep track of any operands that become dead as a result. 8077 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8078 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8079 SDUse &Use = *I++; 8080 SDNode *Used = Use.getNode(); 8081 Use.set(SDValue()); 8082 if (Used->use_empty()) 8083 DeadNodeSet.insert(Used); 8084 } 8085 8086 // For MachineNode, initialize the memory references information. 8087 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8088 MN->clearMemRefs(); 8089 8090 // Swap for an appropriately sized array from the recycler. 8091 removeOperands(N); 8092 createOperands(N, Ops); 8093 8094 // Delete any nodes that are still dead after adding the uses for the 8095 // new operands. 8096 if (!DeadNodeSet.empty()) { 8097 SmallVector<SDNode *, 16> DeadNodes; 8098 for (SDNode *N : DeadNodeSet) 8099 if (N->use_empty()) 8100 DeadNodes.push_back(N); 8101 RemoveDeadNodes(DeadNodes); 8102 } 8103 8104 if (IP) 8105 CSEMap.InsertNode(N, IP); // Memoize the new node. 8106 return N; 8107 } 8108 8109 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8110 unsigned OrigOpc = Node->getOpcode(); 8111 unsigned NewOpc; 8112 switch (OrigOpc) { 8113 default: 8114 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8115 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8116 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8117 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8118 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8119 #include "llvm/IR/ConstrainedOps.def" 8120 } 8121 8122 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8123 8124 // We're taking this node out of the chain, so we need to re-link things. 8125 SDValue InputChain = Node->getOperand(0); 8126 SDValue OutputChain = SDValue(Node, 1); 8127 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8128 8129 SmallVector<SDValue, 3> Ops; 8130 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8131 Ops.push_back(Node->getOperand(i)); 8132 8133 SDVTList VTs = getVTList(Node->getValueType(0)); 8134 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8135 8136 // MorphNodeTo can operate in two ways: if an existing node with the 8137 // specified operands exists, it can just return it. Otherwise, it 8138 // updates the node in place to have the requested operands. 8139 if (Res == Node) { 8140 // If we updated the node in place, reset the node ID. To the isel, 8141 // this should be just like a newly allocated machine node. 8142 Res->setNodeId(-1); 8143 } else { 8144 ReplaceAllUsesWith(Node, Res); 8145 RemoveDeadNode(Node); 8146 } 8147 8148 return Res; 8149 } 8150 8151 /// getMachineNode - These are used for target selectors to create a new node 8152 /// with specified return type(s), MachineInstr opcode, and operands. 8153 /// 8154 /// Note that getMachineNode returns the resultant node. If there is already a 8155 /// node of the specified opcode and operands, it returns that node instead of 8156 /// the current one. 8157 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8158 EVT VT) { 8159 SDVTList VTs = getVTList(VT); 8160 return getMachineNode(Opcode, dl, VTs, None); 8161 } 8162 8163 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8164 EVT VT, SDValue Op1) { 8165 SDVTList VTs = getVTList(VT); 8166 SDValue Ops[] = { Op1 }; 8167 return getMachineNode(Opcode, dl, VTs, Ops); 8168 } 8169 8170 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8171 EVT VT, SDValue Op1, SDValue Op2) { 8172 SDVTList VTs = getVTList(VT); 8173 SDValue Ops[] = { Op1, Op2 }; 8174 return getMachineNode(Opcode, dl, VTs, Ops); 8175 } 8176 8177 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8178 EVT VT, SDValue Op1, SDValue Op2, 8179 SDValue Op3) { 8180 SDVTList VTs = getVTList(VT); 8181 SDValue Ops[] = { Op1, Op2, Op3 }; 8182 return getMachineNode(Opcode, dl, VTs, Ops); 8183 } 8184 8185 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8186 EVT VT, ArrayRef<SDValue> Ops) { 8187 SDVTList VTs = getVTList(VT); 8188 return getMachineNode(Opcode, dl, VTs, Ops); 8189 } 8190 8191 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8192 EVT VT1, EVT VT2, SDValue Op1, 8193 SDValue Op2) { 8194 SDVTList VTs = getVTList(VT1, VT2); 8195 SDValue Ops[] = { Op1, Op2 }; 8196 return getMachineNode(Opcode, dl, VTs, Ops); 8197 } 8198 8199 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8200 EVT VT1, EVT VT2, SDValue Op1, 8201 SDValue Op2, SDValue Op3) { 8202 SDVTList VTs = getVTList(VT1, VT2); 8203 SDValue Ops[] = { Op1, Op2, Op3 }; 8204 return getMachineNode(Opcode, dl, VTs, Ops); 8205 } 8206 8207 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8208 EVT VT1, EVT VT2, 8209 ArrayRef<SDValue> Ops) { 8210 SDVTList VTs = getVTList(VT1, VT2); 8211 return getMachineNode(Opcode, dl, VTs, Ops); 8212 } 8213 8214 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8215 EVT VT1, EVT VT2, EVT VT3, 8216 SDValue Op1, SDValue Op2) { 8217 SDVTList VTs = getVTList(VT1, VT2, VT3); 8218 SDValue Ops[] = { Op1, Op2 }; 8219 return getMachineNode(Opcode, dl, VTs, Ops); 8220 } 8221 8222 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8223 EVT VT1, EVT VT2, EVT VT3, 8224 SDValue Op1, SDValue Op2, 8225 SDValue Op3) { 8226 SDVTList VTs = getVTList(VT1, VT2, VT3); 8227 SDValue Ops[] = { Op1, Op2, Op3 }; 8228 return getMachineNode(Opcode, dl, VTs, Ops); 8229 } 8230 8231 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8232 EVT VT1, EVT VT2, EVT VT3, 8233 ArrayRef<SDValue> Ops) { 8234 SDVTList VTs = getVTList(VT1, VT2, VT3); 8235 return getMachineNode(Opcode, dl, VTs, Ops); 8236 } 8237 8238 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8239 ArrayRef<EVT> ResultTys, 8240 ArrayRef<SDValue> Ops) { 8241 SDVTList VTs = getVTList(ResultTys); 8242 return getMachineNode(Opcode, dl, VTs, Ops); 8243 } 8244 8245 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8246 SDVTList VTs, 8247 ArrayRef<SDValue> Ops) { 8248 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8249 MachineSDNode *N; 8250 void *IP = nullptr; 8251 8252 if (DoCSE) { 8253 FoldingSetNodeID ID; 8254 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8255 IP = nullptr; 8256 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8257 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8258 } 8259 } 8260 8261 // Allocate a new MachineSDNode. 8262 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8263 createOperands(N, Ops); 8264 8265 if (DoCSE) 8266 CSEMap.InsertNode(N, IP); 8267 8268 InsertNode(N); 8269 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8270 return N; 8271 } 8272 8273 /// getTargetExtractSubreg - A convenience function for creating 8274 /// TargetOpcode::EXTRACT_SUBREG nodes. 8275 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8276 SDValue Operand) { 8277 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8278 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8279 VT, Operand, SRIdxVal); 8280 return SDValue(Subreg, 0); 8281 } 8282 8283 /// getTargetInsertSubreg - A convenience function for creating 8284 /// TargetOpcode::INSERT_SUBREG nodes. 8285 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8286 SDValue Operand, SDValue Subreg) { 8287 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8288 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8289 VT, Operand, Subreg, SRIdxVal); 8290 return SDValue(Result, 0); 8291 } 8292 8293 /// getNodeIfExists - Get the specified node if it's already available, or 8294 /// else return NULL. 8295 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8296 ArrayRef<SDValue> Ops) { 8297 SDNodeFlags Flags; 8298 if (Inserter) 8299 Flags = Inserter->getFlags(); 8300 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8301 } 8302 8303 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8304 ArrayRef<SDValue> Ops, 8305 const SDNodeFlags Flags) { 8306 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8307 FoldingSetNodeID ID; 8308 AddNodeIDNode(ID, Opcode, VTList, Ops); 8309 void *IP = nullptr; 8310 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8311 E->intersectFlagsWith(Flags); 8312 return E; 8313 } 8314 } 8315 return nullptr; 8316 } 8317 8318 /// doesNodeExist - Check if a node exists without modifying its flags. 8319 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8320 ArrayRef<SDValue> Ops) { 8321 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8322 FoldingSetNodeID ID; 8323 AddNodeIDNode(ID, Opcode, VTList, Ops); 8324 void *IP = nullptr; 8325 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8326 return true; 8327 } 8328 return false; 8329 } 8330 8331 /// getDbgValue - Creates a SDDbgValue node. 8332 /// 8333 /// SDNode 8334 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8335 SDNode *N, unsigned R, bool IsIndirect, 8336 const DebugLoc &DL, unsigned O) { 8337 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8338 "Expected inlined-at fields to agree"); 8339 return new (DbgInfo->getAlloc()) 8340 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O); 8341 } 8342 8343 /// Constant 8344 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8345 DIExpression *Expr, 8346 const Value *C, 8347 const DebugLoc &DL, unsigned O) { 8348 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8349 "Expected inlined-at fields to agree"); 8350 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O); 8351 } 8352 8353 /// FrameIndex 8354 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8355 DIExpression *Expr, unsigned FI, 8356 bool IsIndirect, 8357 const DebugLoc &DL, 8358 unsigned O) { 8359 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8360 "Expected inlined-at fields to agree"); 8361 return new (DbgInfo->getAlloc()) 8362 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX); 8363 } 8364 8365 /// VReg 8366 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, 8367 DIExpression *Expr, 8368 unsigned VReg, bool IsIndirect, 8369 const DebugLoc &DL, unsigned O) { 8370 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8371 "Expected inlined-at fields to agree"); 8372 return new (DbgInfo->getAlloc()) 8373 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG); 8374 } 8375 8376 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8377 unsigned OffsetInBits, unsigned SizeInBits, 8378 bool InvalidateDbg) { 8379 SDNode *FromNode = From.getNode(); 8380 SDNode *ToNode = To.getNode(); 8381 assert(FromNode && ToNode && "Can't modify dbg values"); 8382 8383 // PR35338 8384 // TODO: assert(From != To && "Redundant dbg value transfer"); 8385 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8386 if (From == To || FromNode == ToNode) 8387 return; 8388 8389 if (!FromNode->getHasDebugValue()) 8390 return; 8391 8392 SmallVector<SDDbgValue *, 2> ClonedDVs; 8393 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8394 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated()) 8395 continue; 8396 8397 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8398 8399 // Just transfer the dbg value attached to From. 8400 if (Dbg->getResNo() != From.getResNo()) 8401 continue; 8402 8403 DIVariable *Var = Dbg->getVariable(); 8404 auto *Expr = Dbg->getExpression(); 8405 // If a fragment is requested, update the expression. 8406 if (SizeInBits) { 8407 // When splitting a larger (e.g., sign-extended) value whose 8408 // lower bits are described with an SDDbgValue, do not attempt 8409 // to transfer the SDDbgValue to the upper bits. 8410 if (auto FI = Expr->getFragmentInfo()) 8411 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8412 continue; 8413 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8414 SizeInBits); 8415 if (!Fragment) 8416 continue; 8417 Expr = *Fragment; 8418 } 8419 // Clone the SDDbgValue and move it to To. 8420 SDDbgValue *Clone = getDbgValue( 8421 Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(), 8422 std::max(ToNode->getIROrder(), Dbg->getOrder())); 8423 ClonedDVs.push_back(Clone); 8424 8425 if (InvalidateDbg) { 8426 // Invalidate value and indicate the SDDbgValue should not be emitted. 8427 Dbg->setIsInvalidated(); 8428 Dbg->setIsEmitted(); 8429 } 8430 } 8431 8432 for (SDDbgValue *Dbg : ClonedDVs) 8433 AddDbgValue(Dbg, ToNode, false); 8434 } 8435 8436 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8437 if (!N.getHasDebugValue()) 8438 return; 8439 8440 SmallVector<SDDbgValue *, 2> ClonedDVs; 8441 for (auto DV : GetDbgValues(&N)) { 8442 if (DV->isInvalidated()) 8443 continue; 8444 switch (N.getOpcode()) { 8445 default: 8446 break; 8447 case ISD::ADD: 8448 SDValue N0 = N.getOperand(0); 8449 SDValue N1 = N.getOperand(1); 8450 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8451 isConstantIntBuildVectorOrConstantInt(N1)) { 8452 uint64_t Offset = N.getConstantOperandVal(1); 8453 // Rewrite an ADD constant node into a DIExpression. Since we are 8454 // performing arithmetic to compute the variable's *value* in the 8455 // DIExpression, we need to mark the expression with a 8456 // DW_OP_stack_value. 8457 auto *DIExpr = DV->getExpression(); 8458 DIExpr = 8459 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset); 8460 SDDbgValue *Clone = 8461 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(), 8462 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder()); 8463 ClonedDVs.push_back(Clone); 8464 DV->setIsInvalidated(); 8465 DV->setIsEmitted(); 8466 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8467 N0.getNode()->dumprFull(this); 8468 dbgs() << " into " << *DIExpr << '\n'); 8469 } 8470 } 8471 } 8472 8473 for (SDDbgValue *Dbg : ClonedDVs) 8474 AddDbgValue(Dbg, Dbg->getSDNode(), false); 8475 } 8476 8477 /// Creates a SDDbgLabel node. 8478 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8479 const DebugLoc &DL, unsigned O) { 8480 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8481 "Expected inlined-at fields to agree"); 8482 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8483 } 8484 8485 namespace { 8486 8487 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8488 /// pointed to by a use iterator is deleted, increment the use iterator 8489 /// so that it doesn't dangle. 8490 /// 8491 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8492 SDNode::use_iterator &UI; 8493 SDNode::use_iterator &UE; 8494 8495 void NodeDeleted(SDNode *N, SDNode *E) override { 8496 // Increment the iterator as needed. 8497 while (UI != UE && N == *UI) 8498 ++UI; 8499 } 8500 8501 public: 8502 RAUWUpdateListener(SelectionDAG &d, 8503 SDNode::use_iterator &ui, 8504 SDNode::use_iterator &ue) 8505 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8506 }; 8507 8508 } // end anonymous namespace 8509 8510 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8511 /// This can cause recursive merging of nodes in the DAG. 8512 /// 8513 /// This version assumes From has a single result value. 8514 /// 8515 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8516 SDNode *From = FromN.getNode(); 8517 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8518 "Cannot replace with this method!"); 8519 assert(From != To.getNode() && "Cannot replace uses of with self"); 8520 8521 // Preserve Debug Values 8522 transferDbgValues(FromN, To); 8523 8524 // Iterate over all the existing uses of From. New uses will be added 8525 // to the beginning of the use list, which we avoid visiting. 8526 // This specifically avoids visiting uses of From that arise while the 8527 // replacement is happening, because any such uses would be the result 8528 // of CSE: If an existing node looks like From after one of its operands 8529 // is replaced by To, we don't want to replace of all its users with To 8530 // too. See PR3018 for more info. 8531 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8532 RAUWUpdateListener Listener(*this, UI, UE); 8533 while (UI != UE) { 8534 SDNode *User = *UI; 8535 8536 // This node is about to morph, remove its old self from the CSE maps. 8537 RemoveNodeFromCSEMaps(User); 8538 8539 // A user can appear in a use list multiple times, and when this 8540 // happens the uses are usually next to each other in the list. 8541 // To help reduce the number of CSE recomputations, process all 8542 // the uses of this user that we can find this way. 8543 do { 8544 SDUse &Use = UI.getUse(); 8545 ++UI; 8546 Use.set(To); 8547 if (To->isDivergent() != From->isDivergent()) 8548 updateDivergence(User); 8549 } while (UI != UE && *UI == User); 8550 // Now that we have modified User, add it back to the CSE maps. If it 8551 // already exists there, recursively merge the results together. 8552 AddModifiedNodeToCSEMaps(User); 8553 } 8554 8555 // If we just RAUW'd the root, take note. 8556 if (FromN == getRoot()) 8557 setRoot(To); 8558 } 8559 8560 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8561 /// This can cause recursive merging of nodes in the DAG. 8562 /// 8563 /// This version assumes that for each value of From, there is a 8564 /// corresponding value in To in the same position with the same type. 8565 /// 8566 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8567 #ifndef NDEBUG 8568 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8569 assert((!From->hasAnyUseOfValue(i) || 8570 From->getValueType(i) == To->getValueType(i)) && 8571 "Cannot use this version of ReplaceAllUsesWith!"); 8572 #endif 8573 8574 // Handle the trivial case. 8575 if (From == To) 8576 return; 8577 8578 // Preserve Debug Info. Only do this if there's a use. 8579 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8580 if (From->hasAnyUseOfValue(i)) { 8581 assert((i < To->getNumValues()) && "Invalid To location"); 8582 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8583 } 8584 8585 // Iterate over just the existing users of From. See the comments in 8586 // the ReplaceAllUsesWith above. 8587 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8588 RAUWUpdateListener Listener(*this, UI, UE); 8589 while (UI != UE) { 8590 SDNode *User = *UI; 8591 8592 // This node is about to morph, remove its old self from the CSE maps. 8593 RemoveNodeFromCSEMaps(User); 8594 8595 // A user can appear in a use list multiple times, and when this 8596 // happens the uses are usually next to each other in the list. 8597 // To help reduce the number of CSE recomputations, process all 8598 // the uses of this user that we can find this way. 8599 do { 8600 SDUse &Use = UI.getUse(); 8601 ++UI; 8602 Use.setNode(To); 8603 if (To->isDivergent() != From->isDivergent()) 8604 updateDivergence(User); 8605 } while (UI != UE && *UI == User); 8606 8607 // Now that we have modified User, add it back to the CSE maps. If it 8608 // already exists there, recursively merge the results together. 8609 AddModifiedNodeToCSEMaps(User); 8610 } 8611 8612 // If we just RAUW'd the root, take note. 8613 if (From == getRoot().getNode()) 8614 setRoot(SDValue(To, getRoot().getResNo())); 8615 } 8616 8617 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8618 /// This can cause recursive merging of nodes in the DAG. 8619 /// 8620 /// This version can replace From with any result values. To must match the 8621 /// number and types of values returned by From. 8622 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8623 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8624 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8625 8626 // Preserve Debug Info. 8627 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8628 transferDbgValues(SDValue(From, i), To[i]); 8629 8630 // Iterate over just the existing users of From. See the comments in 8631 // the ReplaceAllUsesWith above. 8632 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8633 RAUWUpdateListener Listener(*this, UI, UE); 8634 while (UI != UE) { 8635 SDNode *User = *UI; 8636 8637 // This node is about to morph, remove its old self from the CSE maps. 8638 RemoveNodeFromCSEMaps(User); 8639 8640 // A user can appear in a use list multiple times, and when this happens the 8641 // uses are usually next to each other in the list. To help reduce the 8642 // number of CSE and divergence recomputations, process all the uses of this 8643 // user that we can find this way. 8644 bool To_IsDivergent = false; 8645 do { 8646 SDUse &Use = UI.getUse(); 8647 const SDValue &ToOp = To[Use.getResNo()]; 8648 ++UI; 8649 Use.set(ToOp); 8650 To_IsDivergent |= ToOp->isDivergent(); 8651 } while (UI != UE && *UI == User); 8652 8653 if (To_IsDivergent != From->isDivergent()) 8654 updateDivergence(User); 8655 8656 // Now that we have modified User, add it back to the CSE maps. If it 8657 // already exists there, recursively merge the results together. 8658 AddModifiedNodeToCSEMaps(User); 8659 } 8660 8661 // If we just RAUW'd the root, take note. 8662 if (From == getRoot().getNode()) 8663 setRoot(SDValue(To[getRoot().getResNo()])); 8664 } 8665 8666 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8667 /// uses of other values produced by From.getNode() alone. The Deleted 8668 /// vector is handled the same way as for ReplaceAllUsesWith. 8669 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8670 // Handle the really simple, really trivial case efficiently. 8671 if (From == To) return; 8672 8673 // Handle the simple, trivial, case efficiently. 8674 if (From.getNode()->getNumValues() == 1) { 8675 ReplaceAllUsesWith(From, To); 8676 return; 8677 } 8678 8679 // Preserve Debug Info. 8680 transferDbgValues(From, To); 8681 8682 // Iterate over just the existing users of From. See the comments in 8683 // the ReplaceAllUsesWith above. 8684 SDNode::use_iterator UI = From.getNode()->use_begin(), 8685 UE = From.getNode()->use_end(); 8686 RAUWUpdateListener Listener(*this, UI, UE); 8687 while (UI != UE) { 8688 SDNode *User = *UI; 8689 bool UserRemovedFromCSEMaps = false; 8690 8691 // A user can appear in a use list multiple times, and when this 8692 // happens the uses are usually next to each other in the list. 8693 // To help reduce the number of CSE recomputations, process all 8694 // the uses of this user that we can find this way. 8695 do { 8696 SDUse &Use = UI.getUse(); 8697 8698 // Skip uses of different values from the same node. 8699 if (Use.getResNo() != From.getResNo()) { 8700 ++UI; 8701 continue; 8702 } 8703 8704 // If this node hasn't been modified yet, it's still in the CSE maps, 8705 // so remove its old self from the CSE maps. 8706 if (!UserRemovedFromCSEMaps) { 8707 RemoveNodeFromCSEMaps(User); 8708 UserRemovedFromCSEMaps = true; 8709 } 8710 8711 ++UI; 8712 Use.set(To); 8713 if (To->isDivergent() != From->isDivergent()) 8714 updateDivergence(User); 8715 } while (UI != UE && *UI == User); 8716 // We are iterating over all uses of the From node, so if a use 8717 // doesn't use the specific value, no changes are made. 8718 if (!UserRemovedFromCSEMaps) 8719 continue; 8720 8721 // Now that we have modified User, add it back to the CSE maps. If it 8722 // already exists there, recursively merge the results together. 8723 AddModifiedNodeToCSEMaps(User); 8724 } 8725 8726 // If we just RAUW'd the root, take note. 8727 if (From == getRoot()) 8728 setRoot(To); 8729 } 8730 8731 namespace { 8732 8733 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 8734 /// to record information about a use. 8735 struct UseMemo { 8736 SDNode *User; 8737 unsigned Index; 8738 SDUse *Use; 8739 }; 8740 8741 /// operator< - Sort Memos by User. 8742 bool operator<(const UseMemo &L, const UseMemo &R) { 8743 return (intptr_t)L.User < (intptr_t)R.User; 8744 } 8745 8746 } // end anonymous namespace 8747 8748 bool SelectionDAG::calculateDivergence(SDNode *N) { 8749 if (TLI->isSDNodeAlwaysUniform(N)) { 8750 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 8751 "Conflicting divergence information!"); 8752 return false; 8753 } 8754 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 8755 return true; 8756 for (auto &Op : N->ops()) { 8757 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 8758 return true; 8759 } 8760 return false; 8761 } 8762 8763 void SelectionDAG::updateDivergence(SDNode *N) { 8764 SmallVector<SDNode *, 16> Worklist(1, N); 8765 do { 8766 N = Worklist.pop_back_val(); 8767 bool IsDivergent = calculateDivergence(N); 8768 if (N->SDNodeBits.IsDivergent != IsDivergent) { 8769 N->SDNodeBits.IsDivergent = IsDivergent; 8770 Worklist.insert(Worklist.end(), N->use_begin(), N->use_end()); 8771 } 8772 } while (!Worklist.empty()); 8773 } 8774 8775 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 8776 DenseMap<SDNode *, unsigned> Degree; 8777 Order.reserve(AllNodes.size()); 8778 for (auto &N : allnodes()) { 8779 unsigned NOps = N.getNumOperands(); 8780 Degree[&N] = NOps; 8781 if (0 == NOps) 8782 Order.push_back(&N); 8783 } 8784 for (size_t I = 0; I != Order.size(); ++I) { 8785 SDNode *N = Order[I]; 8786 for (auto U : N->uses()) { 8787 unsigned &UnsortedOps = Degree[U]; 8788 if (0 == --UnsortedOps) 8789 Order.push_back(U); 8790 } 8791 } 8792 } 8793 8794 #ifndef NDEBUG 8795 void SelectionDAG::VerifyDAGDiverence() { 8796 std::vector<SDNode *> TopoOrder; 8797 CreateTopologicalOrder(TopoOrder); 8798 for (auto *N : TopoOrder) { 8799 assert(calculateDivergence(N) == N->isDivergent() && 8800 "Divergence bit inconsistency detected"); 8801 } 8802 } 8803 #endif 8804 8805 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 8806 /// uses of other values produced by From.getNode() alone. The same value 8807 /// may appear in both the From and To list. The Deleted vector is 8808 /// handled the same way as for ReplaceAllUsesWith. 8809 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 8810 const SDValue *To, 8811 unsigned Num){ 8812 // Handle the simple, trivial case efficiently. 8813 if (Num == 1) 8814 return ReplaceAllUsesOfValueWith(*From, *To); 8815 8816 transferDbgValues(*From, *To); 8817 8818 // Read up all the uses and make records of them. This helps 8819 // processing new uses that are introduced during the 8820 // replacement process. 8821 SmallVector<UseMemo, 4> Uses; 8822 for (unsigned i = 0; i != Num; ++i) { 8823 unsigned FromResNo = From[i].getResNo(); 8824 SDNode *FromNode = From[i].getNode(); 8825 for (SDNode::use_iterator UI = FromNode->use_begin(), 8826 E = FromNode->use_end(); UI != E; ++UI) { 8827 SDUse &Use = UI.getUse(); 8828 if (Use.getResNo() == FromResNo) { 8829 UseMemo Memo = { *UI, i, &Use }; 8830 Uses.push_back(Memo); 8831 } 8832 } 8833 } 8834 8835 // Sort the uses, so that all the uses from a given User are together. 8836 llvm::sort(Uses); 8837 8838 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 8839 UseIndex != UseIndexEnd; ) { 8840 // We know that this user uses some value of From. If it is the right 8841 // value, update it. 8842 SDNode *User = Uses[UseIndex].User; 8843 8844 // This node is about to morph, remove its old self from the CSE maps. 8845 RemoveNodeFromCSEMaps(User); 8846 8847 // The Uses array is sorted, so all the uses for a given User 8848 // are next to each other in the list. 8849 // To help reduce the number of CSE recomputations, process all 8850 // the uses of this user that we can find this way. 8851 do { 8852 unsigned i = Uses[UseIndex].Index; 8853 SDUse &Use = *Uses[UseIndex].Use; 8854 ++UseIndex; 8855 8856 Use.set(To[i]); 8857 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 8858 8859 // Now that we have modified User, add it back to the CSE maps. If it 8860 // already exists there, recursively merge the results together. 8861 AddModifiedNodeToCSEMaps(User); 8862 } 8863 } 8864 8865 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 8866 /// based on their topological order. It returns the maximum id and a vector 8867 /// of the SDNodes* in assigned order by reference. 8868 unsigned SelectionDAG::AssignTopologicalOrder() { 8869 unsigned DAGSize = 0; 8870 8871 // SortedPos tracks the progress of the algorithm. Nodes before it are 8872 // sorted, nodes after it are unsorted. When the algorithm completes 8873 // it is at the end of the list. 8874 allnodes_iterator SortedPos = allnodes_begin(); 8875 8876 // Visit all the nodes. Move nodes with no operands to the front of 8877 // the list immediately. Annotate nodes that do have operands with their 8878 // operand count. Before we do this, the Node Id fields of the nodes 8879 // may contain arbitrary values. After, the Node Id fields for nodes 8880 // before SortedPos will contain the topological sort index, and the 8881 // Node Id fields for nodes At SortedPos and after will contain the 8882 // count of outstanding operands. 8883 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 8884 SDNode *N = &*I++; 8885 checkForCycles(N, this); 8886 unsigned Degree = N->getNumOperands(); 8887 if (Degree == 0) { 8888 // A node with no uses, add it to the result array immediately. 8889 N->setNodeId(DAGSize++); 8890 allnodes_iterator Q(N); 8891 if (Q != SortedPos) 8892 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 8893 assert(SortedPos != AllNodes.end() && "Overran node list"); 8894 ++SortedPos; 8895 } else { 8896 // Temporarily use the Node Id as scratch space for the degree count. 8897 N->setNodeId(Degree); 8898 } 8899 } 8900 8901 // Visit all the nodes. As we iterate, move nodes into sorted order, 8902 // such that by the time the end is reached all nodes will be sorted. 8903 for (SDNode &Node : allnodes()) { 8904 SDNode *N = &Node; 8905 checkForCycles(N, this); 8906 // N is in sorted position, so all its uses have one less operand 8907 // that needs to be sorted. 8908 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8909 UI != UE; ++UI) { 8910 SDNode *P = *UI; 8911 unsigned Degree = P->getNodeId(); 8912 assert(Degree != 0 && "Invalid node degree"); 8913 --Degree; 8914 if (Degree == 0) { 8915 // All of P's operands are sorted, so P may sorted now. 8916 P->setNodeId(DAGSize++); 8917 if (P->getIterator() != SortedPos) 8918 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 8919 assert(SortedPos != AllNodes.end() && "Overran node list"); 8920 ++SortedPos; 8921 } else { 8922 // Update P's outstanding operand count. 8923 P->setNodeId(Degree); 8924 } 8925 } 8926 if (Node.getIterator() == SortedPos) { 8927 #ifndef NDEBUG 8928 allnodes_iterator I(N); 8929 SDNode *S = &*++I; 8930 dbgs() << "Overran sorted position:\n"; 8931 S->dumprFull(this); dbgs() << "\n"; 8932 dbgs() << "Checking if this is due to cycles\n"; 8933 checkForCycles(this, true); 8934 #endif 8935 llvm_unreachable(nullptr); 8936 } 8937 } 8938 8939 assert(SortedPos == AllNodes.end() && 8940 "Topological sort incomplete!"); 8941 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 8942 "First node in topological sort is not the entry token!"); 8943 assert(AllNodes.front().getNodeId() == 0 && 8944 "First node in topological sort has non-zero id!"); 8945 assert(AllNodes.front().getNumOperands() == 0 && 8946 "First node in topological sort has operands!"); 8947 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 8948 "Last node in topologic sort has unexpected id!"); 8949 assert(AllNodes.back().use_empty() && 8950 "Last node in topologic sort has users!"); 8951 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 8952 return DAGSize; 8953 } 8954 8955 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 8956 /// value is produced by SD. 8957 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 8958 if (SD) { 8959 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 8960 SD->setHasDebugValue(true); 8961 } 8962 DbgInfo->add(DB, SD, isParameter); 8963 } 8964 8965 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { 8966 DbgInfo->add(DB); 8967 } 8968 8969 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 8970 SDValue NewMemOp) { 8971 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 8972 // The new memory operation must have the same position as the old load in 8973 // terms of memory dependency. Create a TokenFactor for the old load and new 8974 // memory operation and update uses of the old load's output chain to use that 8975 // TokenFactor. 8976 SDValue OldChain = SDValue(OldLoad, 1); 8977 SDValue NewChain = SDValue(NewMemOp.getNode(), 1); 8978 if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1)) 8979 return NewChain; 8980 8981 SDValue TokenFactor = 8982 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain); 8983 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 8984 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain); 8985 return TokenFactor; 8986 } 8987 8988 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 8989 Function **OutFunction) { 8990 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 8991 8992 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 8993 auto *Module = MF->getFunction().getParent(); 8994 auto *Function = Module->getFunction(Symbol); 8995 8996 if (OutFunction != nullptr) 8997 *OutFunction = Function; 8998 8999 if (Function != nullptr) { 9000 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9001 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9002 } 9003 9004 std::string ErrorStr; 9005 raw_string_ostream ErrorFormatter(ErrorStr); 9006 9007 ErrorFormatter << "Undefined external symbol "; 9008 ErrorFormatter << '"' << Symbol << '"'; 9009 ErrorFormatter.flush(); 9010 9011 report_fatal_error(ErrorStr); 9012 } 9013 9014 //===----------------------------------------------------------------------===// 9015 // SDNode Class 9016 //===----------------------------------------------------------------------===// 9017 9018 bool llvm::isNullConstant(SDValue V) { 9019 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9020 return Const != nullptr && Const->isNullValue(); 9021 } 9022 9023 bool llvm::isNullFPConstant(SDValue V) { 9024 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9025 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9026 } 9027 9028 bool llvm::isAllOnesConstant(SDValue V) { 9029 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9030 return Const != nullptr && Const->isAllOnesValue(); 9031 } 9032 9033 bool llvm::isOneConstant(SDValue V) { 9034 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9035 return Const != nullptr && Const->isOne(); 9036 } 9037 9038 SDValue llvm::peekThroughBitcasts(SDValue V) { 9039 while (V.getOpcode() == ISD::BITCAST) 9040 V = V.getOperand(0); 9041 return V; 9042 } 9043 9044 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9045 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9046 V = V.getOperand(0); 9047 return V; 9048 } 9049 9050 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9051 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9052 V = V.getOperand(0); 9053 return V; 9054 } 9055 9056 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9057 if (V.getOpcode() != ISD::XOR) 9058 return false; 9059 V = peekThroughBitcasts(V.getOperand(1)); 9060 unsigned NumBits = V.getScalarValueSizeInBits(); 9061 ConstantSDNode *C = 9062 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9063 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9064 } 9065 9066 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9067 bool AllowTruncation) { 9068 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9069 return CN; 9070 9071 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9072 BitVector UndefElements; 9073 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9074 9075 // BuildVectors can truncate their operands. Ignore that case here unless 9076 // AllowTruncation is set. 9077 if (CN && (UndefElements.none() || AllowUndefs)) { 9078 EVT CVT = CN->getValueType(0); 9079 EVT NSVT = N.getValueType().getScalarType(); 9080 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9081 if (AllowTruncation || (CVT == NSVT)) 9082 return CN; 9083 } 9084 } 9085 9086 return nullptr; 9087 } 9088 9089 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9090 bool AllowUndefs, 9091 bool AllowTruncation) { 9092 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9093 return CN; 9094 9095 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9096 BitVector UndefElements; 9097 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9098 9099 // BuildVectors can truncate their operands. Ignore that case here unless 9100 // AllowTruncation is set. 9101 if (CN && (UndefElements.none() || AllowUndefs)) { 9102 EVT CVT = CN->getValueType(0); 9103 EVT NSVT = N.getValueType().getScalarType(); 9104 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9105 if (AllowTruncation || (CVT == NSVT)) 9106 return CN; 9107 } 9108 } 9109 9110 return nullptr; 9111 } 9112 9113 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9114 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9115 return CN; 9116 9117 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9118 BitVector UndefElements; 9119 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9120 if (CN && (UndefElements.none() || AllowUndefs)) 9121 return CN; 9122 } 9123 9124 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9125 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9126 return CN; 9127 9128 return nullptr; 9129 } 9130 9131 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9132 const APInt &DemandedElts, 9133 bool AllowUndefs) { 9134 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9135 return CN; 9136 9137 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9138 BitVector UndefElements; 9139 ConstantFPSDNode *CN = 9140 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9141 if (CN && (UndefElements.none() || AllowUndefs)) 9142 return CN; 9143 } 9144 9145 return nullptr; 9146 } 9147 9148 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9149 // TODO: may want to use peekThroughBitcast() here. 9150 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9151 return C && C->isNullValue(); 9152 } 9153 9154 bool llvm::isOneOrOneSplat(SDValue N) { 9155 // TODO: may want to use peekThroughBitcast() here. 9156 unsigned BitWidth = N.getScalarValueSizeInBits(); 9157 ConstantSDNode *C = isConstOrConstSplat(N); 9158 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9159 } 9160 9161 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) { 9162 N = peekThroughBitcasts(N); 9163 unsigned BitWidth = N.getScalarValueSizeInBits(); 9164 ConstantSDNode *C = isConstOrConstSplat(N); 9165 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9166 } 9167 9168 HandleSDNode::~HandleSDNode() { 9169 DropOperands(); 9170 } 9171 9172 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9173 const DebugLoc &DL, 9174 const GlobalValue *GA, EVT VT, 9175 int64_t o, unsigned TF) 9176 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9177 TheGlobal = GA; 9178 } 9179 9180 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9181 EVT VT, unsigned SrcAS, 9182 unsigned DestAS) 9183 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9184 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9185 9186 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9187 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9188 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9189 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9190 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9191 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9192 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9193 9194 // We check here that the size of the memory operand fits within the size of 9195 // the MMO. This is because the MMO might indicate only a possible address 9196 // range instead of specifying the affected memory addresses precisely. 9197 // TODO: Make MachineMemOperands aware of scalable vectors. 9198 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9199 "Size mismatch!"); 9200 } 9201 9202 /// Profile - Gather unique data for the node. 9203 /// 9204 void SDNode::Profile(FoldingSetNodeID &ID) const { 9205 AddNodeIDNode(ID, this); 9206 } 9207 9208 namespace { 9209 9210 struct EVTArray { 9211 std::vector<EVT> VTs; 9212 9213 EVTArray() { 9214 VTs.reserve(MVT::LAST_VALUETYPE); 9215 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9216 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9217 } 9218 }; 9219 9220 } // end anonymous namespace 9221 9222 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9223 static ManagedStatic<EVTArray> SimpleVTArray; 9224 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9225 9226 /// getValueTypeList - Return a pointer to the specified value type. 9227 /// 9228 const EVT *SDNode::getValueTypeList(EVT VT) { 9229 if (VT.isExtended()) { 9230 sys::SmartScopedLock<true> Lock(*VTMutex); 9231 return &(*EVTs->insert(VT).first); 9232 } else { 9233 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 9234 "Value type out of range!"); 9235 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9236 } 9237 } 9238 9239 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9240 /// indicated value. This method ignores uses of other values defined by this 9241 /// operation. 9242 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9243 assert(Value < getNumValues() && "Bad value!"); 9244 9245 // TODO: Only iterate over uses of a given value of the node 9246 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9247 if (UI.getUse().getResNo() == Value) { 9248 if (NUses == 0) 9249 return false; 9250 --NUses; 9251 } 9252 } 9253 9254 // Found exactly the right number of uses? 9255 return NUses == 0; 9256 } 9257 9258 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9259 /// value. This method ignores uses of other values defined by this operation. 9260 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9261 assert(Value < getNumValues() && "Bad value!"); 9262 9263 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9264 if (UI.getUse().getResNo() == Value) 9265 return true; 9266 9267 return false; 9268 } 9269 9270 /// isOnlyUserOf - Return true if this node is the only use of N. 9271 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9272 bool Seen = false; 9273 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9274 SDNode *User = *I; 9275 if (User == this) 9276 Seen = true; 9277 else 9278 return false; 9279 } 9280 9281 return Seen; 9282 } 9283 9284 /// Return true if the only users of N are contained in Nodes. 9285 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9286 bool Seen = false; 9287 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9288 SDNode *User = *I; 9289 if (llvm::is_contained(Nodes, User)) 9290 Seen = true; 9291 else 9292 return false; 9293 } 9294 9295 return Seen; 9296 } 9297 9298 /// isOperand - Return true if this node is an operand of N. 9299 bool SDValue::isOperandOf(const SDNode *N) const { 9300 return is_contained(N->op_values(), *this); 9301 } 9302 9303 bool SDNode::isOperandOf(const SDNode *N) const { 9304 return any_of(N->op_values(), 9305 [this](SDValue Op) { return this == Op.getNode(); }); 9306 } 9307 9308 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9309 /// be a chain) reaches the specified operand without crossing any 9310 /// side-effecting instructions on any chain path. In practice, this looks 9311 /// through token factors and non-volatile loads. In order to remain efficient, 9312 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9313 /// 9314 /// Note that we only need to examine chains when we're searching for 9315 /// side-effects; SelectionDAG requires that all side-effects are represented 9316 /// by chains, even if another operand would force a specific ordering. This 9317 /// constraint is necessary to allow transformations like splitting loads. 9318 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9319 unsigned Depth) const { 9320 if (*this == Dest) return true; 9321 9322 // Don't search too deeply, we just want to be able to see through 9323 // TokenFactor's etc. 9324 if (Depth == 0) return false; 9325 9326 // If this is a token factor, all inputs to the TF happen in parallel. 9327 if (getOpcode() == ISD::TokenFactor) { 9328 // First, try a shallow search. 9329 if (is_contained((*this)->ops(), Dest)) { 9330 // We found the chain we want as an operand of this TokenFactor. 9331 // Essentially, we reach the chain without side-effects if we could 9332 // serialize the TokenFactor into a simple chain of operations with 9333 // Dest as the last operation. This is automatically true if the 9334 // chain has one use: there are no other ordering constraints. 9335 // If the chain has more than one use, we give up: some other 9336 // use of Dest might force a side-effect between Dest and the current 9337 // node. 9338 if (Dest.hasOneUse()) 9339 return true; 9340 } 9341 // Next, try a deep search: check whether every operand of the TokenFactor 9342 // reaches Dest. 9343 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9344 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9345 }); 9346 } 9347 9348 // Loads don't have side effects, look through them. 9349 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9350 if (Ld->isUnordered()) 9351 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9352 } 9353 return false; 9354 } 9355 9356 bool SDNode::hasPredecessor(const SDNode *N) const { 9357 SmallPtrSet<const SDNode *, 32> Visited; 9358 SmallVector<const SDNode *, 16> Worklist; 9359 Worklist.push_back(this); 9360 return hasPredecessorHelper(N, Visited, Worklist); 9361 } 9362 9363 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9364 this->Flags.intersectWith(Flags); 9365 } 9366 9367 SDValue 9368 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9369 ArrayRef<ISD::NodeType> CandidateBinOps, 9370 bool AllowPartials) { 9371 // The pattern must end in an extract from index 0. 9372 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9373 !isNullConstant(Extract->getOperand(1))) 9374 return SDValue(); 9375 9376 // Match against one of the candidate binary ops. 9377 SDValue Op = Extract->getOperand(0); 9378 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9379 return Op.getOpcode() == unsigned(BinOp); 9380 })) 9381 return SDValue(); 9382 9383 // Floating-point reductions may require relaxed constraints on the final step 9384 // of the reduction because they may reorder intermediate operations. 9385 unsigned CandidateBinOp = Op.getOpcode(); 9386 if (Op.getValueType().isFloatingPoint()) { 9387 SDNodeFlags Flags = Op->getFlags(); 9388 switch (CandidateBinOp) { 9389 case ISD::FADD: 9390 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9391 return SDValue(); 9392 break; 9393 default: 9394 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9395 } 9396 } 9397 9398 // Matching failed - attempt to see if we did enough stages that a partial 9399 // reduction from a subvector is possible. 9400 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9401 if (!AllowPartials || !Op) 9402 return SDValue(); 9403 EVT OpVT = Op.getValueType(); 9404 EVT OpSVT = OpVT.getScalarType(); 9405 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9406 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9407 return SDValue(); 9408 BinOp = (ISD::NodeType)CandidateBinOp; 9409 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9410 getVectorIdxConstant(0, SDLoc(Op))); 9411 }; 9412 9413 // At each stage, we're looking for something that looks like: 9414 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9415 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9416 // i32 undef, i32 undef, i32 undef, i32 undef> 9417 // %a = binop <8 x i32> %op, %s 9418 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9419 // we expect something like: 9420 // <4,5,6,7,u,u,u,u> 9421 // <2,3,u,u,u,u,u,u> 9422 // <1,u,u,u,u,u,u,u> 9423 // While a partial reduction match would be: 9424 // <2,3,u,u,u,u,u,u> 9425 // <1,u,u,u,u,u,u,u> 9426 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9427 SDValue PrevOp; 9428 for (unsigned i = 0; i < Stages; ++i) { 9429 unsigned MaskEnd = (1 << i); 9430 9431 if (Op.getOpcode() != CandidateBinOp) 9432 return PartialReduction(PrevOp, MaskEnd); 9433 9434 SDValue Op0 = Op.getOperand(0); 9435 SDValue Op1 = Op.getOperand(1); 9436 9437 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9438 if (Shuffle) { 9439 Op = Op1; 9440 } else { 9441 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9442 Op = Op0; 9443 } 9444 9445 // The first operand of the shuffle should be the same as the other operand 9446 // of the binop. 9447 if (!Shuffle || Shuffle->getOperand(0) != Op) 9448 return PartialReduction(PrevOp, MaskEnd); 9449 9450 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9451 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9452 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9453 return PartialReduction(PrevOp, MaskEnd); 9454 9455 PrevOp = Op; 9456 } 9457 9458 // Handle subvector reductions, which tend to appear after the shuffle 9459 // reduction stages. 9460 while (Op.getOpcode() == CandidateBinOp) { 9461 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9462 SDValue Op0 = Op.getOperand(0); 9463 SDValue Op1 = Op.getOperand(1); 9464 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9465 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9466 Op0.getOperand(0) != Op1.getOperand(0)) 9467 break; 9468 SDValue Src = Op0.getOperand(0); 9469 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9470 if (NumSrcElts != (2 * NumElts)) 9471 break; 9472 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9473 Op1.getConstantOperandAPInt(1) == NumElts) && 9474 !(Op1.getConstantOperandAPInt(1) == 0 && 9475 Op0.getConstantOperandAPInt(1) == NumElts)) 9476 break; 9477 Op = Src; 9478 } 9479 9480 BinOp = (ISD::NodeType)CandidateBinOp; 9481 return Op; 9482 } 9483 9484 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9485 assert(N->getNumValues() == 1 && 9486 "Can't unroll a vector with multiple results!"); 9487 9488 EVT VT = N->getValueType(0); 9489 unsigned NE = VT.getVectorNumElements(); 9490 EVT EltVT = VT.getVectorElementType(); 9491 SDLoc dl(N); 9492 9493 SmallVector<SDValue, 8> Scalars; 9494 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9495 9496 // If ResNE is 0, fully unroll the vector op. 9497 if (ResNE == 0) 9498 ResNE = NE; 9499 else if (NE > ResNE) 9500 NE = ResNE; 9501 9502 unsigned i; 9503 for (i= 0; i != NE; ++i) { 9504 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9505 SDValue Operand = N->getOperand(j); 9506 EVT OperandVT = Operand.getValueType(); 9507 if (OperandVT.isVector()) { 9508 // A vector operand; extract a single element. 9509 EVT OperandEltVT = OperandVT.getVectorElementType(); 9510 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9511 Operand, getVectorIdxConstant(i, dl)); 9512 } else { 9513 // A scalar operand; just use it as is. 9514 Operands[j] = Operand; 9515 } 9516 } 9517 9518 switch (N->getOpcode()) { 9519 default: { 9520 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9521 N->getFlags())); 9522 break; 9523 } 9524 case ISD::VSELECT: 9525 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9526 break; 9527 case ISD::SHL: 9528 case ISD::SRA: 9529 case ISD::SRL: 9530 case ISD::ROTL: 9531 case ISD::ROTR: 9532 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9533 getShiftAmountOperand(Operands[0].getValueType(), 9534 Operands[1]))); 9535 break; 9536 case ISD::SIGN_EXTEND_INREG: { 9537 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9538 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9539 Operands[0], 9540 getValueType(ExtVT))); 9541 } 9542 } 9543 } 9544 9545 for (; i < ResNE; ++i) 9546 Scalars.push_back(getUNDEF(EltVT)); 9547 9548 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9549 return getBuildVector(VecVT, dl, Scalars); 9550 } 9551 9552 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9553 SDNode *N, unsigned ResNE) { 9554 unsigned Opcode = N->getOpcode(); 9555 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9556 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9557 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9558 "Expected an overflow opcode"); 9559 9560 EVT ResVT = N->getValueType(0); 9561 EVT OvVT = N->getValueType(1); 9562 EVT ResEltVT = ResVT.getVectorElementType(); 9563 EVT OvEltVT = OvVT.getVectorElementType(); 9564 SDLoc dl(N); 9565 9566 // If ResNE is 0, fully unroll the vector op. 9567 unsigned NE = ResVT.getVectorNumElements(); 9568 if (ResNE == 0) 9569 ResNE = NE; 9570 else if (NE > ResNE) 9571 NE = ResNE; 9572 9573 SmallVector<SDValue, 8> LHSScalars; 9574 SmallVector<SDValue, 8> RHSScalars; 9575 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9576 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9577 9578 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9579 SDVTList VTs = getVTList(ResEltVT, SVT); 9580 SmallVector<SDValue, 8> ResScalars; 9581 SmallVector<SDValue, 8> OvScalars; 9582 for (unsigned i = 0; i < NE; ++i) { 9583 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9584 SDValue Ov = 9585 getSelect(dl, OvEltVT, Res.getValue(1), 9586 getBoolConstant(true, dl, OvEltVT, ResVT), 9587 getConstant(0, dl, OvEltVT)); 9588 9589 ResScalars.push_back(Res); 9590 OvScalars.push_back(Ov); 9591 } 9592 9593 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9594 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9595 9596 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9597 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9598 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9599 getBuildVector(NewOvVT, dl, OvScalars)); 9600 } 9601 9602 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9603 LoadSDNode *Base, 9604 unsigned Bytes, 9605 int Dist) const { 9606 if (LD->isVolatile() || Base->isVolatile()) 9607 return false; 9608 // TODO: probably too restrictive for atomics, revisit 9609 if (!LD->isSimple()) 9610 return false; 9611 if (LD->isIndexed() || Base->isIndexed()) 9612 return false; 9613 if (LD->getChain() != Base->getChain()) 9614 return false; 9615 EVT VT = LD->getValueType(0); 9616 if (VT.getSizeInBits() / 8 != Bytes) 9617 return false; 9618 9619 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9620 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9621 9622 int64_t Offset = 0; 9623 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9624 return (Dist * Bytes == Offset); 9625 return false; 9626 } 9627 9628 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 9629 /// if it cannot be inferred. 9630 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 9631 // If this is a GlobalAddress + cst, return the alignment. 9632 const GlobalValue *GV = nullptr; 9633 int64_t GVOffset = 0; 9634 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9635 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 9636 KnownBits Known(PtrWidth); 9637 llvm::computeKnownBits(GV, Known, getDataLayout()); 9638 unsigned AlignBits = Known.countMinTrailingZeros(); 9639 if (AlignBits) 9640 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 9641 } 9642 9643 // If this is a direct reference to a stack slot, use information about the 9644 // stack slot's alignment. 9645 int FrameIdx = INT_MIN; 9646 int64_t FrameOffset = 0; 9647 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9648 FrameIdx = FI->getIndex(); 9649 } else if (isBaseWithConstantOffset(Ptr) && 9650 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9651 // Handle FI+Cst 9652 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9653 FrameOffset = Ptr.getConstantOperandVal(1); 9654 } 9655 9656 if (FrameIdx != INT_MIN) { 9657 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9658 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 9659 } 9660 9661 return None; 9662 } 9663 9664 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9665 /// which is split (or expanded) into two not necessarily identical pieces. 9666 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9667 // Currently all types are split in half. 9668 EVT LoVT, HiVT; 9669 if (!VT.isVector()) 9670 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9671 else 9672 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9673 9674 return std::make_pair(LoVT, HiVT); 9675 } 9676 9677 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 9678 /// type, dependent on an enveloping VT that has been split into two identical 9679 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 9680 std::pair<EVT, EVT> 9681 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 9682 bool *HiIsEmpty) const { 9683 EVT EltTp = VT.getVectorElementType(); 9684 // Examples: 9685 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 9686 // custom VL=9 with enveloping VL=8/8 yields 8/1 9687 // custom VL=10 with enveloping VL=8/8 yields 8/2 9688 // etc. 9689 ElementCount VTNumElts = VT.getVectorElementCount(); 9690 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 9691 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 9692 "Mixing fixed width and scalable vectors when enveloping a type"); 9693 EVT LoVT, HiVT; 9694 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 9695 LoVT = EnvVT; 9696 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 9697 *HiIsEmpty = false; 9698 } else { 9699 // Flag that hi type has zero storage size, but return split envelop type 9700 // (this would be easier if vector types with zero elements were allowed). 9701 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 9702 HiVT = EnvVT; 9703 *HiIsEmpty = true; 9704 } 9705 return std::make_pair(LoVT, HiVT); 9706 } 9707 9708 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 9709 /// low/high part. 9710 std::pair<SDValue, SDValue> 9711 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 9712 const EVT &HiVT) { 9713 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 9714 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 9715 "Splitting vector with an invalid mixture of fixed and scalable " 9716 "vector types"); 9717 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 9718 N.getValueType().getVectorMinNumElements() && 9719 "More vector elements requested than available!"); 9720 SDValue Lo, Hi; 9721 Lo = 9722 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 9723 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 9724 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 9725 // IDX with the runtime scaling factor of the result vector type. For 9726 // fixed-width result vectors, that runtime scaling factor is 1. 9727 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 9728 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 9729 return std::make_pair(Lo, Hi); 9730 } 9731 9732 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 9733 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 9734 EVT VT = N.getValueType(); 9735 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 9736 NextPowerOf2(VT.getVectorNumElements())); 9737 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 9738 getVectorIdxConstant(0, DL)); 9739 } 9740 9741 void SelectionDAG::ExtractVectorElements(SDValue Op, 9742 SmallVectorImpl<SDValue> &Args, 9743 unsigned Start, unsigned Count, 9744 EVT EltVT) { 9745 EVT VT = Op.getValueType(); 9746 if (Count == 0) 9747 Count = VT.getVectorNumElements(); 9748 if (EltVT == EVT()) 9749 EltVT = VT.getVectorElementType(); 9750 SDLoc SL(Op); 9751 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 9752 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 9753 getVectorIdxConstant(i, SL))); 9754 } 9755 } 9756 9757 // getAddressSpace - Return the address space this GlobalAddress belongs to. 9758 unsigned GlobalAddressSDNode::getAddressSpace() const { 9759 return getGlobal()->getType()->getAddressSpace(); 9760 } 9761 9762 Type *ConstantPoolSDNode::getType() const { 9763 if (isMachineConstantPoolEntry()) 9764 return Val.MachineCPVal->getType(); 9765 return Val.ConstVal->getType(); 9766 } 9767 9768 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 9769 unsigned &SplatBitSize, 9770 bool &HasAnyUndefs, 9771 unsigned MinSplatBits, 9772 bool IsBigEndian) const { 9773 EVT VT = getValueType(0); 9774 assert(VT.isVector() && "Expected a vector type"); 9775 unsigned VecWidth = VT.getSizeInBits(); 9776 if (MinSplatBits > VecWidth) 9777 return false; 9778 9779 // FIXME: The widths are based on this node's type, but build vectors can 9780 // truncate their operands. 9781 SplatValue = APInt(VecWidth, 0); 9782 SplatUndef = APInt(VecWidth, 0); 9783 9784 // Get the bits. Bits with undefined values (when the corresponding element 9785 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 9786 // in SplatValue. If any of the values are not constant, give up and return 9787 // false. 9788 unsigned int NumOps = getNumOperands(); 9789 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 9790 unsigned EltWidth = VT.getScalarSizeInBits(); 9791 9792 for (unsigned j = 0; j < NumOps; ++j) { 9793 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 9794 SDValue OpVal = getOperand(i); 9795 unsigned BitPos = j * EltWidth; 9796 9797 if (OpVal.isUndef()) 9798 SplatUndef.setBits(BitPos, BitPos + EltWidth); 9799 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 9800 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 9801 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 9802 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 9803 else 9804 return false; 9805 } 9806 9807 // The build_vector is all constants or undefs. Find the smallest element 9808 // size that splats the vector. 9809 HasAnyUndefs = (SplatUndef != 0); 9810 9811 // FIXME: This does not work for vectors with elements less than 8 bits. 9812 while (VecWidth > 8) { 9813 unsigned HalfSize = VecWidth / 2; 9814 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 9815 APInt LowValue = SplatValue.trunc(HalfSize); 9816 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 9817 APInt LowUndef = SplatUndef.trunc(HalfSize); 9818 9819 // If the two halves do not match (ignoring undef bits), stop here. 9820 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 9821 MinSplatBits > HalfSize) 9822 break; 9823 9824 SplatValue = HighValue | LowValue; 9825 SplatUndef = HighUndef & LowUndef; 9826 9827 VecWidth = HalfSize; 9828 } 9829 9830 SplatBitSize = VecWidth; 9831 return true; 9832 } 9833 9834 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 9835 BitVector *UndefElements) const { 9836 unsigned NumOps = getNumOperands(); 9837 if (UndefElements) { 9838 UndefElements->clear(); 9839 UndefElements->resize(NumOps); 9840 } 9841 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 9842 if (!DemandedElts) 9843 return SDValue(); 9844 SDValue Splatted; 9845 for (unsigned i = 0; i != NumOps; ++i) { 9846 if (!DemandedElts[i]) 9847 continue; 9848 SDValue Op = getOperand(i); 9849 if (Op.isUndef()) { 9850 if (UndefElements) 9851 (*UndefElements)[i] = true; 9852 } else if (!Splatted) { 9853 Splatted = Op; 9854 } else if (Splatted != Op) { 9855 return SDValue(); 9856 } 9857 } 9858 9859 if (!Splatted) { 9860 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 9861 assert(getOperand(FirstDemandedIdx).isUndef() && 9862 "Can only have a splat without a constant for all undefs."); 9863 return getOperand(FirstDemandedIdx); 9864 } 9865 9866 return Splatted; 9867 } 9868 9869 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 9870 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 9871 return getSplatValue(DemandedElts, UndefElements); 9872 } 9873 9874 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 9875 SmallVectorImpl<SDValue> &Sequence, 9876 BitVector *UndefElements) const { 9877 unsigned NumOps = getNumOperands(); 9878 Sequence.clear(); 9879 if (UndefElements) { 9880 UndefElements->clear(); 9881 UndefElements->resize(NumOps); 9882 } 9883 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 9884 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 9885 return false; 9886 9887 // Set the undefs even if we don't find a sequence (like getSplatValue). 9888 if (UndefElements) 9889 for (unsigned I = 0; I != NumOps; ++I) 9890 if (DemandedElts[I] && getOperand(I).isUndef()) 9891 (*UndefElements)[I] = true; 9892 9893 // Iteratively widen the sequence length looking for repetitions. 9894 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 9895 Sequence.append(SeqLen, SDValue()); 9896 for (unsigned I = 0; I != NumOps; ++I) { 9897 if (!DemandedElts[I]) 9898 continue; 9899 SDValue &SeqOp = Sequence[I % SeqLen]; 9900 SDValue Op = getOperand(I); 9901 if (Op.isUndef()) { 9902 if (!SeqOp) 9903 SeqOp = Op; 9904 continue; 9905 } 9906 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 9907 Sequence.clear(); 9908 break; 9909 } 9910 SeqOp = Op; 9911 } 9912 if (!Sequence.empty()) 9913 return true; 9914 } 9915 9916 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 9917 return false; 9918 } 9919 9920 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 9921 BitVector *UndefElements) const { 9922 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 9923 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 9924 } 9925 9926 ConstantSDNode * 9927 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 9928 BitVector *UndefElements) const { 9929 return dyn_cast_or_null<ConstantSDNode>( 9930 getSplatValue(DemandedElts, UndefElements)); 9931 } 9932 9933 ConstantSDNode * 9934 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 9935 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 9936 } 9937 9938 ConstantFPSDNode * 9939 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 9940 BitVector *UndefElements) const { 9941 return dyn_cast_or_null<ConstantFPSDNode>( 9942 getSplatValue(DemandedElts, UndefElements)); 9943 } 9944 9945 ConstantFPSDNode * 9946 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 9947 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 9948 } 9949 9950 int32_t 9951 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 9952 uint32_t BitWidth) const { 9953 if (ConstantFPSDNode *CN = 9954 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 9955 bool IsExact; 9956 APSInt IntVal(BitWidth); 9957 const APFloat &APF = CN->getValueAPF(); 9958 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 9959 APFloat::opOK || 9960 !IsExact) 9961 return -1; 9962 9963 return IntVal.exactLogBase2(); 9964 } 9965 return -1; 9966 } 9967 9968 bool BuildVectorSDNode::isConstant() const { 9969 for (const SDValue &Op : op_values()) { 9970 unsigned Opc = Op.getOpcode(); 9971 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 9972 return false; 9973 } 9974 return true; 9975 } 9976 9977 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 9978 // Find the first non-undef value in the shuffle mask. 9979 unsigned i, e; 9980 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 9981 /* search */; 9982 9983 // If all elements are undefined, this shuffle can be considered a splat 9984 // (although it should eventually get simplified away completely). 9985 if (i == e) 9986 return true; 9987 9988 // Make sure all remaining elements are either undef or the same as the first 9989 // non-undef value. 9990 for (int Idx = Mask[i]; i != e; ++i) 9991 if (Mask[i] >= 0 && Mask[i] != Idx) 9992 return false; 9993 return true; 9994 } 9995 9996 // Returns the SDNode if it is a constant integer BuildVector 9997 // or constant integer. 9998 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 9999 if (isa<ConstantSDNode>(N)) 10000 return N.getNode(); 10001 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10002 return N.getNode(); 10003 // Treat a GlobalAddress supporting constant offset folding as a 10004 // constant integer. 10005 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10006 if (GA->getOpcode() == ISD::GlobalAddress && 10007 TLI->isOffsetFoldingLegal(GA)) 10008 return GA; 10009 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10010 isa<ConstantSDNode>(N.getOperand(0))) 10011 return N.getNode(); 10012 return nullptr; 10013 } 10014 10015 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) { 10016 if (isa<ConstantFPSDNode>(N)) 10017 return N.getNode(); 10018 10019 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10020 return N.getNode(); 10021 10022 return nullptr; 10023 } 10024 10025 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10026 assert(!Node->OperandList && "Node already has operands"); 10027 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10028 "too many operands to fit into SDNode"); 10029 SDUse *Ops = OperandRecycler.allocate( 10030 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10031 10032 bool IsDivergent = false; 10033 for (unsigned I = 0; I != Vals.size(); ++I) { 10034 Ops[I].setUser(Node); 10035 Ops[I].setInitial(Vals[I]); 10036 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10037 IsDivergent |= Ops[I].getNode()->isDivergent(); 10038 } 10039 Node->NumOperands = Vals.size(); 10040 Node->OperandList = Ops; 10041 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10042 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10043 Node->SDNodeBits.IsDivergent = IsDivergent; 10044 } 10045 checkForCycles(Node); 10046 } 10047 10048 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10049 SmallVectorImpl<SDValue> &Vals) { 10050 size_t Limit = SDNode::getMaxNumOperands(); 10051 while (Vals.size() > Limit) { 10052 unsigned SliceIdx = Vals.size() - Limit; 10053 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10054 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10055 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10056 Vals.emplace_back(NewTF); 10057 } 10058 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10059 } 10060 10061 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10062 EVT VT, SDNodeFlags Flags) { 10063 switch (Opcode) { 10064 default: 10065 return SDValue(); 10066 case ISD::ADD: 10067 case ISD::OR: 10068 case ISD::XOR: 10069 case ISD::UMAX: 10070 return getConstant(0, DL, VT); 10071 case ISD::MUL: 10072 return getConstant(1, DL, VT); 10073 case ISD::AND: 10074 case ISD::UMIN: 10075 return getAllOnesConstant(DL, VT); 10076 case ISD::SMAX: 10077 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10078 case ISD::SMIN: 10079 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10080 case ISD::FADD: 10081 return getConstantFP(-0.0, DL, VT); 10082 case ISD::FMUL: 10083 return getConstantFP(1.0, DL, VT); 10084 case ISD::FMINNUM: 10085 case ISD::FMAXNUM: { 10086 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10087 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10088 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10089 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10090 APFloat::getLargest(Semantics); 10091 if (Opcode == ISD::FMAXNUM) 10092 NeutralAF.changeSign(); 10093 10094 return getConstantFP(NeutralAF, DL, VT); 10095 } 10096 } 10097 } 10098 10099 #ifndef NDEBUG 10100 static void checkForCyclesHelper(const SDNode *N, 10101 SmallPtrSetImpl<const SDNode*> &Visited, 10102 SmallPtrSetImpl<const SDNode*> &Checked, 10103 const llvm::SelectionDAG *DAG) { 10104 // If this node has already been checked, don't check it again. 10105 if (Checked.count(N)) 10106 return; 10107 10108 // If a node has already been visited on this depth-first walk, reject it as 10109 // a cycle. 10110 if (!Visited.insert(N).second) { 10111 errs() << "Detected cycle in SelectionDAG\n"; 10112 dbgs() << "Offending node:\n"; 10113 N->dumprFull(DAG); dbgs() << "\n"; 10114 abort(); 10115 } 10116 10117 for (const SDValue &Op : N->op_values()) 10118 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10119 10120 Checked.insert(N); 10121 Visited.erase(N); 10122 } 10123 #endif 10124 10125 void llvm::checkForCycles(const llvm::SDNode *N, 10126 const llvm::SelectionDAG *DAG, 10127 bool force) { 10128 #ifndef NDEBUG 10129 bool check = force; 10130 #ifdef EXPENSIVE_CHECKS 10131 check = true; 10132 #endif // EXPENSIVE_CHECKS 10133 if (check) { 10134 assert(N && "Checking nonexistent SDNode"); 10135 SmallPtrSet<const SDNode*, 32> visited; 10136 SmallPtrSet<const SDNode*, 32> checked; 10137 checkForCyclesHelper(N, visited, checked, DAG); 10138 } 10139 #endif // !NDEBUG 10140 } 10141 10142 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10143 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10144 } 10145