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