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