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