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