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