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