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