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