1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/TargetLowering.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Analysis/VectorUtils.h" 16 #include "llvm/CodeGen/CallingConvLower.h" 17 #include "llvm/CodeGen/CodeGenCommonISel.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineJumpTableInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/TargetRegisterInfo.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/MC/MCAsmInfo.h" 29 #include "llvm/MC/MCExpr.h" 30 #include "llvm/Support/DivisionByConstantInfo.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/KnownBits.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Target/TargetMachine.h" 35 #include <cctype> 36 using namespace llvm; 37 38 /// NOTE: The TargetMachine owns TLOF. 39 TargetLowering::TargetLowering(const TargetMachine &tm) 40 : TargetLoweringBase(tm) {} 41 42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 43 return nullptr; 44 } 45 46 bool TargetLowering::isPositionIndependent() const { 47 return getTargetMachine().isPositionIndependent(); 48 } 49 50 /// Check whether a given call node is in tail position within its function. If 51 /// so, it sets Chain to the input chain of the tail call. 52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 53 SDValue &Chain) const { 54 const Function &F = DAG.getMachineFunction().getFunction(); 55 56 // First, check if tail calls have been disabled in this function. 57 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 58 return false; 59 60 // Conservatively require the attributes of the call to match those of 61 // the return. Ignore following attributes because they don't affect the 62 // call sequence. 63 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 64 for (const auto &Attr : 65 {Attribute::Alignment, Attribute::Dereferenceable, 66 Attribute::DereferenceableOrNull, Attribute::NoAlias, 67 Attribute::NonNull, Attribute::NoUndef, Attribute::Range}) 68 CallerAttrs.removeAttribute(Attr); 69 70 if (CallerAttrs.hasAttributes()) 71 return false; 72 73 // It's not safe to eliminate the sign / zero extension of the return value. 74 if (CallerAttrs.contains(Attribute::ZExt) || 75 CallerAttrs.contains(Attribute::SExt)) 76 return false; 77 78 // Check if the only use is a function return node. 79 return isUsedByReturnOnly(Node, Chain); 80 } 81 82 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 83 const uint32_t *CallerPreservedMask, 84 const SmallVectorImpl<CCValAssign> &ArgLocs, 85 const SmallVectorImpl<SDValue> &OutVals) const { 86 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 87 const CCValAssign &ArgLoc = ArgLocs[I]; 88 if (!ArgLoc.isRegLoc()) 89 continue; 90 MCRegister Reg = ArgLoc.getLocReg(); 91 // Only look at callee saved registers. 92 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 93 continue; 94 // Check that we pass the value used for the caller. 95 // (We look for a CopyFromReg reading a virtual register that is used 96 // for the function live-in value of register Reg) 97 SDValue Value = OutVals[I]; 98 if (Value->getOpcode() == ISD::AssertZext) 99 Value = Value.getOperand(0); 100 if (Value->getOpcode() != ISD::CopyFromReg) 101 return false; 102 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 103 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 104 return false; 105 } 106 return true; 107 } 108 109 /// Set CallLoweringInfo attribute flags based on a call instruction 110 /// and called function attributes. 111 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 112 unsigned ArgIdx) { 113 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 114 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 115 IsNoExt = Call->paramHasAttr(ArgIdx, Attribute::NoExt); 116 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 117 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 118 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 119 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 120 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 121 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 122 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 123 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 124 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 125 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 126 Alignment = Call->getParamStackAlign(ArgIdx); 127 IndirectType = nullptr; 128 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 129 "multiple ABI attributes?"); 130 if (IsByVal) { 131 IndirectType = Call->getParamByValType(ArgIdx); 132 if (!Alignment) 133 Alignment = Call->getParamAlign(ArgIdx); 134 } 135 if (IsPreallocated) 136 IndirectType = Call->getParamPreallocatedType(ArgIdx); 137 if (IsInAlloca) 138 IndirectType = Call->getParamInAllocaType(ArgIdx); 139 if (IsSRet) 140 IndirectType = Call->getParamStructRetType(ArgIdx); 141 } 142 143 /// Generate a libcall taking the given operands as arguments and returning a 144 /// result of type RetVT. 145 std::pair<SDValue, SDValue> 146 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 147 ArrayRef<SDValue> Ops, 148 MakeLibCallOptions CallOptions, 149 const SDLoc &dl, 150 SDValue InChain) const { 151 if (!InChain) 152 InChain = DAG.getEntryNode(); 153 154 TargetLowering::ArgListTy Args; 155 Args.reserve(Ops.size()); 156 157 TargetLowering::ArgListEntry Entry; 158 for (unsigned i = 0; i < Ops.size(); ++i) { 159 SDValue NewOp = Ops[i]; 160 Entry.Node = NewOp; 161 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 162 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 163 CallOptions.IsSExt); 164 Entry.IsZExt = !Entry.IsSExt; 165 166 if (CallOptions.IsSoften && 167 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 168 Entry.IsSExt = Entry.IsZExt = false; 169 } 170 Args.push_back(Entry); 171 } 172 173 if (LC == RTLIB::UNKNOWN_LIBCALL) 174 report_fatal_error("Unsupported library call operation!"); 175 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 176 getPointerTy(DAG.getDataLayout())); 177 178 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 179 TargetLowering::CallLoweringInfo CLI(DAG); 180 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 181 bool zeroExtend = !signExtend; 182 183 if (CallOptions.IsSoften && 184 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 185 signExtend = zeroExtend = false; 186 } 187 188 CLI.setDebugLoc(dl) 189 .setChain(InChain) 190 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 191 .setNoReturn(CallOptions.DoesNotReturn) 192 .setDiscardResult(!CallOptions.IsReturnValueUsed) 193 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 194 .setSExtResult(signExtend) 195 .setZExtResult(zeroExtend); 196 return LowerCallTo(CLI); 197 } 198 199 bool TargetLowering::findOptimalMemOpLowering( 200 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 201 unsigned SrcAS, const AttributeList &FuncAttributes) const { 202 if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() && 203 Op.getSrcAlign() < Op.getDstAlign()) 204 return false; 205 206 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 207 208 if (VT == MVT::Other) { 209 // Use the largest integer type whose alignment constraints are satisfied. 210 // We only need to check DstAlign here as SrcAlign is always greater or 211 // equal to DstAlign (or zero). 212 VT = MVT::LAST_INTEGER_VALUETYPE; 213 if (Op.isFixedDstAlign()) 214 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 215 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 216 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 217 assert(VT.isInteger()); 218 219 // Find the largest legal integer type. 220 MVT LVT = MVT::LAST_INTEGER_VALUETYPE; 221 while (!isTypeLegal(LVT)) 222 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 223 assert(LVT.isInteger()); 224 225 // If the type we've chosen is larger than the largest legal integer type 226 // then use that instead. 227 if (VT.bitsGT(LVT)) 228 VT = LVT; 229 } 230 231 unsigned NumMemOps = 0; 232 uint64_t Size = Op.size(); 233 while (Size) { 234 unsigned VTSize = VT.getSizeInBits() / 8; 235 while (VTSize > Size) { 236 // For now, only use non-vector load / store's for the left-over pieces. 237 EVT NewVT = VT; 238 unsigned NewVTSize; 239 240 bool Found = false; 241 if (VT.isVector() || VT.isFloatingPoint()) { 242 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 243 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 244 isSafeMemOpType(NewVT.getSimpleVT())) 245 Found = true; 246 else if (NewVT == MVT::i64 && 247 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 248 isSafeMemOpType(MVT::f64)) { 249 // i64 is usually not legal on 32-bit targets, but f64 may be. 250 NewVT = MVT::f64; 251 Found = true; 252 } 253 } 254 255 if (!Found) { 256 do { 257 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 258 if (NewVT == MVT::i8) 259 break; 260 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 261 } 262 NewVTSize = NewVT.getSizeInBits() / 8; 263 264 // If the new VT cannot cover all of the remaining bits, then consider 265 // issuing a (or a pair of) unaligned and overlapping load / store. 266 unsigned Fast; 267 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 268 allowsMisalignedMemoryAccesses( 269 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 270 MachineMemOperand::MONone, &Fast) && 271 Fast) 272 VTSize = Size; 273 else { 274 VT = NewVT; 275 VTSize = NewVTSize; 276 } 277 } 278 279 if (++NumMemOps > Limit) 280 return false; 281 282 MemOps.push_back(VT); 283 Size -= VTSize; 284 } 285 286 return true; 287 } 288 289 /// Soften the operands of a comparison. This code is shared among BR_CC, 290 /// SELECT_CC, and SETCC handlers. 291 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 292 SDValue &NewLHS, SDValue &NewRHS, 293 ISD::CondCode &CCCode, 294 const SDLoc &dl, const SDValue OldLHS, 295 const SDValue OldRHS) const { 296 SDValue Chain; 297 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 298 OldRHS, Chain); 299 } 300 301 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 302 SDValue &NewLHS, SDValue &NewRHS, 303 ISD::CondCode &CCCode, 304 const SDLoc &dl, const SDValue OldLHS, 305 const SDValue OldRHS, 306 SDValue &Chain, 307 bool IsSignaling) const { 308 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 309 // not supporting it. We can update this code when libgcc provides such 310 // functions. 311 312 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 313 && "Unsupported setcc type!"); 314 315 // Expand into one or more soft-fp libcall(s). 316 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 317 bool ShouldInvertCC = false; 318 switch (CCCode) { 319 case ISD::SETEQ: 320 case ISD::SETOEQ: 321 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 322 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 323 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 324 break; 325 case ISD::SETNE: 326 case ISD::SETUNE: 327 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 328 (VT == MVT::f64) ? RTLIB::UNE_F64 : 329 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 330 break; 331 case ISD::SETGE: 332 case ISD::SETOGE: 333 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 334 (VT == MVT::f64) ? RTLIB::OGE_F64 : 335 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 336 break; 337 case ISD::SETLT: 338 case ISD::SETOLT: 339 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 340 (VT == MVT::f64) ? RTLIB::OLT_F64 : 341 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 342 break; 343 case ISD::SETLE: 344 case ISD::SETOLE: 345 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 346 (VT == MVT::f64) ? RTLIB::OLE_F64 : 347 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 348 break; 349 case ISD::SETGT: 350 case ISD::SETOGT: 351 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 352 (VT == MVT::f64) ? RTLIB::OGT_F64 : 353 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 354 break; 355 case ISD::SETO: 356 ShouldInvertCC = true; 357 [[fallthrough]]; 358 case ISD::SETUO: 359 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 360 (VT == MVT::f64) ? RTLIB::UO_F64 : 361 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 362 break; 363 case ISD::SETONE: 364 // SETONE = O && UNE 365 ShouldInvertCC = true; 366 [[fallthrough]]; 367 case ISD::SETUEQ: 368 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 369 (VT == MVT::f64) ? RTLIB::UO_F64 : 370 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 371 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 372 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 373 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 374 break; 375 default: 376 // Invert CC for unordered comparisons 377 ShouldInvertCC = true; 378 switch (CCCode) { 379 case ISD::SETULT: 380 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 381 (VT == MVT::f64) ? RTLIB::OGE_F64 : 382 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 383 break; 384 case ISD::SETULE: 385 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 386 (VT == MVT::f64) ? RTLIB::OGT_F64 : 387 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 388 break; 389 case ISD::SETUGT: 390 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 391 (VT == MVT::f64) ? RTLIB::OLE_F64 : 392 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 393 break; 394 case ISD::SETUGE: 395 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 396 (VT == MVT::f64) ? RTLIB::OLT_F64 : 397 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 398 break; 399 default: llvm_unreachable("Do not know how to soften this setcc!"); 400 } 401 } 402 403 // Use the target specific return value for comparison lib calls. 404 EVT RetVT = getCmpLibcallReturnType(); 405 SDValue Ops[2] = {NewLHS, NewRHS}; 406 TargetLowering::MakeLibCallOptions CallOptions; 407 EVT OpsVT[2] = { OldLHS.getValueType(), 408 OldRHS.getValueType() }; 409 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 410 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 411 NewLHS = Call.first; 412 NewRHS = DAG.getConstant(0, dl, RetVT); 413 414 CCCode = getCmpLibcallCC(LC1); 415 if (ShouldInvertCC) { 416 assert(RetVT.isInteger()); 417 CCCode = getSetCCInverse(CCCode, RetVT); 418 } 419 420 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 421 // Update Chain. 422 Chain = Call.second; 423 } else { 424 EVT SetCCVT = 425 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 426 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 427 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 428 CCCode = getCmpLibcallCC(LC2); 429 if (ShouldInvertCC) 430 CCCode = getSetCCInverse(CCCode, RetVT); 431 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 432 if (Chain) 433 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 434 Call2.second); 435 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 436 Tmp.getValueType(), Tmp, NewLHS); 437 NewRHS = SDValue(); 438 } 439 } 440 441 /// Return the entry encoding for a jump table in the current function. The 442 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 443 unsigned TargetLowering::getJumpTableEncoding() const { 444 // In non-pic modes, just use the address of a block. 445 if (!isPositionIndependent()) 446 return MachineJumpTableInfo::EK_BlockAddress; 447 448 // In PIC mode, if the target supports a GPRel32 directive, use it. 449 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 450 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 451 452 // Otherwise, use a label difference. 453 return MachineJumpTableInfo::EK_LabelDifference32; 454 } 455 456 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 457 SelectionDAG &DAG) const { 458 // If our PIC model is GP relative, use the global offset table as the base. 459 unsigned JTEncoding = getJumpTableEncoding(); 460 461 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 462 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 463 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 464 465 return Table; 466 } 467 468 /// This returns the relocation base for the given PIC jumptable, the same as 469 /// getPICJumpTableRelocBase, but as an MCExpr. 470 const MCExpr * 471 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 472 unsigned JTI,MCContext &Ctx) const{ 473 // The normal PIC reloc base is the label at the start of the jump table. 474 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 475 } 476 477 SDValue TargetLowering::expandIndirectJTBranch(const SDLoc &dl, SDValue Value, 478 SDValue Addr, int JTI, 479 SelectionDAG &DAG) const { 480 SDValue Chain = Value; 481 // Jump table debug info is only needed if CodeView is enabled. 482 if (DAG.getTarget().getTargetTriple().isOSBinFormatCOFF()) { 483 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl); 484 } 485 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr); 486 } 487 488 bool 489 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 490 const TargetMachine &TM = getTargetMachine(); 491 const GlobalValue *GV = GA->getGlobal(); 492 493 // If the address is not even local to this DSO we will have to load it from 494 // a got and then add the offset. 495 if (!TM.shouldAssumeDSOLocal(GV)) 496 return false; 497 498 // If the code is position independent we will have to add a base register. 499 if (isPositionIndependent()) 500 return false; 501 502 // Otherwise we can do it. 503 return true; 504 } 505 506 //===----------------------------------------------------------------------===// 507 // Optimization Methods 508 //===----------------------------------------------------------------------===// 509 510 /// If the specified instruction has a constant integer operand and there are 511 /// bits set in that constant that are not demanded, then clear those bits and 512 /// return true. 513 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 514 const APInt &DemandedBits, 515 const APInt &DemandedElts, 516 TargetLoweringOpt &TLO) const { 517 SDLoc DL(Op); 518 unsigned Opcode = Op.getOpcode(); 519 520 // Early-out if we've ended up calling an undemanded node, leave this to 521 // constant folding. 522 if (DemandedBits.isZero() || DemandedElts.isZero()) 523 return false; 524 525 // Do target-specific constant optimization. 526 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 527 return TLO.New.getNode(); 528 529 // FIXME: ISD::SELECT, ISD::SELECT_CC 530 switch (Opcode) { 531 default: 532 break; 533 case ISD::XOR: 534 case ISD::AND: 535 case ISD::OR: { 536 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 537 if (!Op1C || Op1C->isOpaque()) 538 return false; 539 540 // If this is a 'not' op, don't touch it because that's a canonical form. 541 const APInt &C = Op1C->getAPIntValue(); 542 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 543 return false; 544 545 if (!C.isSubsetOf(DemandedBits)) { 546 EVT VT = Op.getValueType(); 547 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 548 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC, 549 Op->getFlags()); 550 return TLO.CombineTo(Op, NewOp); 551 } 552 553 break; 554 } 555 } 556 557 return false; 558 } 559 560 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 561 const APInt &DemandedBits, 562 TargetLoweringOpt &TLO) const { 563 EVT VT = Op.getValueType(); 564 APInt DemandedElts = VT.isVector() 565 ? APInt::getAllOnes(VT.getVectorNumElements()) 566 : APInt(1, 1); 567 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 568 } 569 570 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 571 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast, 572 /// but it could be generalized for targets with other types of implicit 573 /// widening casts. 574 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 575 const APInt &DemandedBits, 576 TargetLoweringOpt &TLO) const { 577 assert(Op.getNumOperands() == 2 && 578 "ShrinkDemandedOp only supports binary operators!"); 579 assert(Op.getNode()->getNumValues() == 1 && 580 "ShrinkDemandedOp only supports nodes with one result!"); 581 582 EVT VT = Op.getValueType(); 583 SelectionDAG &DAG = TLO.DAG; 584 SDLoc dl(Op); 585 586 // Early return, as this function cannot handle vector types. 587 if (VT.isVector()) 588 return false; 589 590 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth && 591 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth && 592 "ShrinkDemandedOp only supports operands that have the same size!"); 593 594 // Don't do this if the node has another user, which may require the 595 // full value. 596 if (!Op.getNode()->hasOneUse()) 597 return false; 598 599 // Search for the smallest integer type with free casts to and from 600 // Op's type. For expedience, just check power-of-2 integer types. 601 unsigned DemandedSize = DemandedBits.getActiveBits(); 602 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize); 603 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 604 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 605 if (isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT)) { 606 // We found a type with free casts. 607 608 // If the operation has the 'disjoint' flag, then the 609 // operands on the new node are also disjoint. 610 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint 611 : SDNodeFlags::None); 612 SDValue X = DAG.getNode( 613 Op.getOpcode(), dl, SmallVT, 614 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 615 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags); 616 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 617 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X); 618 return TLO.CombineTo(Op, Z); 619 } 620 } 621 return false; 622 } 623 624 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 625 DAGCombinerInfo &DCI) const { 626 SelectionDAG &DAG = DCI.DAG; 627 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 628 !DCI.isBeforeLegalizeOps()); 629 KnownBits Known; 630 631 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 632 if (Simplified) { 633 DCI.AddToWorklist(Op.getNode()); 634 DCI.CommitTargetLoweringOpt(TLO); 635 } 636 return Simplified; 637 } 638 639 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 640 const APInt &DemandedElts, 641 DAGCombinerInfo &DCI) const { 642 SelectionDAG &DAG = DCI.DAG; 643 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 644 !DCI.isBeforeLegalizeOps()); 645 KnownBits Known; 646 647 bool Simplified = 648 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 649 if (Simplified) { 650 DCI.AddToWorklist(Op.getNode()); 651 DCI.CommitTargetLoweringOpt(TLO); 652 } 653 return Simplified; 654 } 655 656 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 657 KnownBits &Known, 658 TargetLoweringOpt &TLO, 659 unsigned Depth, 660 bool AssumeSingleUse) const { 661 EVT VT = Op.getValueType(); 662 663 // Since the number of lanes in a scalable vector is unknown at compile time, 664 // we track one bit which is implicitly broadcast to all lanes. This means 665 // that all lanes in a scalable vector are considered demanded. 666 APInt DemandedElts = VT.isFixedLengthVector() 667 ? APInt::getAllOnes(VT.getVectorNumElements()) 668 : APInt(1, 1); 669 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 670 AssumeSingleUse); 671 } 672 673 // TODO: Under what circumstances can we create nodes? Constant folding? 674 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 675 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 676 SelectionDAG &DAG, unsigned Depth) const { 677 EVT VT = Op.getValueType(); 678 679 // Limit search depth. 680 if (Depth >= SelectionDAG::MaxRecursionDepth) 681 return SDValue(); 682 683 // Ignore UNDEFs. 684 if (Op.isUndef()) 685 return SDValue(); 686 687 // Not demanding any bits/elts from Op. 688 if (DemandedBits == 0 || DemandedElts == 0) 689 return DAG.getUNDEF(VT); 690 691 bool IsLE = DAG.getDataLayout().isLittleEndian(); 692 unsigned NumElts = DemandedElts.getBitWidth(); 693 unsigned BitWidth = DemandedBits.getBitWidth(); 694 KnownBits LHSKnown, RHSKnown; 695 switch (Op.getOpcode()) { 696 case ISD::BITCAST: { 697 if (VT.isScalableVector()) 698 return SDValue(); 699 700 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 701 EVT SrcVT = Src.getValueType(); 702 EVT DstVT = Op.getValueType(); 703 if (SrcVT == DstVT) 704 return Src; 705 706 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 707 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 708 if (NumSrcEltBits == NumDstEltBits) 709 if (SDValue V = SimplifyMultipleUseDemandedBits( 710 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 711 return DAG.getBitcast(DstVT, V); 712 713 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 714 unsigned Scale = NumDstEltBits / NumSrcEltBits; 715 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 716 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 717 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 718 for (unsigned i = 0; i != Scale; ++i) { 719 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 720 unsigned BitOffset = EltOffset * NumSrcEltBits; 721 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 722 if (!Sub.isZero()) { 723 DemandedSrcBits |= Sub; 724 for (unsigned j = 0; j != NumElts; ++j) 725 if (DemandedElts[j]) 726 DemandedSrcElts.setBit((j * Scale) + i); 727 } 728 } 729 730 if (SDValue V = SimplifyMultipleUseDemandedBits( 731 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 732 return DAG.getBitcast(DstVT, V); 733 } 734 735 // TODO - bigendian once we have test coverage. 736 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 737 unsigned Scale = NumSrcEltBits / NumDstEltBits; 738 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 739 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 740 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 741 for (unsigned i = 0; i != NumElts; ++i) 742 if (DemandedElts[i]) { 743 unsigned Offset = (i % Scale) * NumDstEltBits; 744 DemandedSrcBits.insertBits(DemandedBits, Offset); 745 DemandedSrcElts.setBit(i / Scale); 746 } 747 748 if (SDValue V = SimplifyMultipleUseDemandedBits( 749 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 750 return DAG.getBitcast(DstVT, V); 751 } 752 753 break; 754 } 755 case ISD::FREEZE: { 756 SDValue N0 = Op.getOperand(0); 757 if (DAG.isGuaranteedNotToBeUndefOrPoison(N0, DemandedElts, 758 /*PoisonOnly=*/false)) 759 return N0; 760 break; 761 } 762 case ISD::AND: { 763 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 764 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 765 766 // If all of the demanded bits are known 1 on one side, return the other. 767 // These bits cannot contribute to the result of the 'and' in this 768 // context. 769 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 770 return Op.getOperand(0); 771 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 772 return Op.getOperand(1); 773 break; 774 } 775 case ISD::OR: { 776 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 777 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 778 779 // If all of the demanded bits are known zero on one side, return the 780 // other. These bits cannot contribute to the result of the 'or' in this 781 // context. 782 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 783 return Op.getOperand(0); 784 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 785 return Op.getOperand(1); 786 break; 787 } 788 case ISD::XOR: { 789 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 790 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 791 792 // If all of the demanded bits are known zero on one side, return the 793 // other. 794 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 795 return Op.getOperand(0); 796 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 797 return Op.getOperand(1); 798 break; 799 } 800 case ISD::ADD: { 801 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 802 if (RHSKnown.isZero()) 803 return Op.getOperand(0); 804 805 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 806 if (LHSKnown.isZero()) 807 return Op.getOperand(1); 808 break; 809 } 810 case ISD::SHL: { 811 // If we are only demanding sign bits then we can use the shift source 812 // directly. 813 if (std::optional<uint64_t> MaxSA = 814 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 815 SDValue Op0 = Op.getOperand(0); 816 unsigned ShAmt = *MaxSA; 817 unsigned NumSignBits = 818 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 819 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 820 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 821 return Op0; 822 } 823 break; 824 } 825 case ISD::SRL: { 826 // If we are only demanding sign bits then we can use the shift source 827 // directly. 828 if (std::optional<uint64_t> MaxSA = 829 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 830 SDValue Op0 = Op.getOperand(0); 831 unsigned ShAmt = *MaxSA; 832 // Must already be signbits in DemandedBits bounds, and can't demand any 833 // shifted in zeroes. 834 if (DemandedBits.countl_zero() >= ShAmt) { 835 unsigned NumSignBits = 836 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 837 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits)) 838 return Op0; 839 } 840 } 841 break; 842 } 843 case ISD::SETCC: { 844 SDValue Op0 = Op.getOperand(0); 845 SDValue Op1 = Op.getOperand(1); 846 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 847 // If (1) we only need the sign-bit, (2) the setcc operands are the same 848 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 849 // -1, we may be able to bypass the setcc. 850 if (DemandedBits.isSignMask() && 851 Op0.getScalarValueSizeInBits() == BitWidth && 852 getBooleanContents(Op0.getValueType()) == 853 BooleanContent::ZeroOrNegativeOneBooleanContent) { 854 // If we're testing X < 0, then this compare isn't needed - just use X! 855 // FIXME: We're limiting to integer types here, but this should also work 856 // if we don't care about FP signed-zero. The use of SETLT with FP means 857 // that we don't care about NaNs. 858 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 859 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 860 return Op0; 861 } 862 break; 863 } 864 case ISD::SIGN_EXTEND_INREG: { 865 // If none of the extended bits are demanded, eliminate the sextinreg. 866 SDValue Op0 = Op.getOperand(0); 867 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 868 unsigned ExBits = ExVT.getScalarSizeInBits(); 869 if (DemandedBits.getActiveBits() <= ExBits && 870 shouldRemoveRedundantExtend(Op)) 871 return Op0; 872 // If the input is already sign extended, just drop the extension. 873 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 874 if (NumSignBits >= (BitWidth - ExBits + 1)) 875 return Op0; 876 break; 877 } 878 case ISD::ANY_EXTEND_VECTOR_INREG: 879 case ISD::SIGN_EXTEND_VECTOR_INREG: 880 case ISD::ZERO_EXTEND_VECTOR_INREG: { 881 if (VT.isScalableVector()) 882 return SDValue(); 883 884 // If we only want the lowest element and none of extended bits, then we can 885 // return the bitcasted source vector. 886 SDValue Src = Op.getOperand(0); 887 EVT SrcVT = Src.getValueType(); 888 EVT DstVT = Op.getValueType(); 889 if (IsLE && DemandedElts == 1 && 890 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 891 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 892 return DAG.getBitcast(DstVT, Src); 893 } 894 break; 895 } 896 case ISD::INSERT_VECTOR_ELT: { 897 if (VT.isScalableVector()) 898 return SDValue(); 899 900 // If we don't demand the inserted element, return the base vector. 901 SDValue Vec = Op.getOperand(0); 902 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 903 EVT VecVT = Vec.getValueType(); 904 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 905 !DemandedElts[CIdx->getZExtValue()]) 906 return Vec; 907 break; 908 } 909 case ISD::INSERT_SUBVECTOR: { 910 if (VT.isScalableVector()) 911 return SDValue(); 912 913 SDValue Vec = Op.getOperand(0); 914 SDValue Sub = Op.getOperand(1); 915 uint64_t Idx = Op.getConstantOperandVal(2); 916 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 917 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 918 // If we don't demand the inserted subvector, return the base vector. 919 if (DemandedSubElts == 0) 920 return Vec; 921 break; 922 } 923 case ISD::VECTOR_SHUFFLE: { 924 assert(!VT.isScalableVector()); 925 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 926 927 // If all the demanded elts are from one operand and are inline, 928 // then we can use the operand directly. 929 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 930 for (unsigned i = 0; i != NumElts; ++i) { 931 int M = ShuffleMask[i]; 932 if (M < 0 || !DemandedElts[i]) 933 continue; 934 AllUndef = false; 935 IdentityLHS &= (M == (int)i); 936 IdentityRHS &= ((M - NumElts) == i); 937 } 938 939 if (AllUndef) 940 return DAG.getUNDEF(Op.getValueType()); 941 if (IdentityLHS) 942 return Op.getOperand(0); 943 if (IdentityRHS) 944 return Op.getOperand(1); 945 break; 946 } 947 default: 948 // TODO: Probably okay to remove after audit; here to reduce change size 949 // in initial enablement patch for scalable vectors 950 if (VT.isScalableVector()) 951 return SDValue(); 952 953 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 954 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 955 Op, DemandedBits, DemandedElts, DAG, Depth)) 956 return V; 957 break; 958 } 959 return SDValue(); 960 } 961 962 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 963 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 964 unsigned Depth) const { 965 EVT VT = Op.getValueType(); 966 // Since the number of lanes in a scalable vector is unknown at compile time, 967 // we track one bit which is implicitly broadcast to all lanes. This means 968 // that all lanes in a scalable vector are considered demanded. 969 APInt DemandedElts = VT.isFixedLengthVector() 970 ? APInt::getAllOnes(VT.getVectorNumElements()) 971 : APInt(1, 1); 972 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 973 Depth); 974 } 975 976 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 977 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 978 unsigned Depth) const { 979 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 980 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 981 Depth); 982 } 983 984 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 985 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 986 static SDValue combineShiftToAVG(SDValue Op, 987 TargetLowering::TargetLoweringOpt &TLO, 988 const TargetLowering &TLI, 989 const APInt &DemandedBits, 990 const APInt &DemandedElts, unsigned Depth) { 991 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 992 "SRL or SRA node is required here!"); 993 // Is the right shift using an immediate value of 1? 994 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 995 if (!N1C || !N1C->isOne()) 996 return SDValue(); 997 998 // We are looking for an avgfloor 999 // add(ext, ext) 1000 // or one of these as a avgceil 1001 // add(add(ext, ext), 1) 1002 // add(add(ext, 1), ext) 1003 // add(ext, add(ext, 1)) 1004 SDValue Add = Op.getOperand(0); 1005 if (Add.getOpcode() != ISD::ADD) 1006 return SDValue(); 1007 1008 SDValue ExtOpA = Add.getOperand(0); 1009 SDValue ExtOpB = Add.getOperand(1); 1010 SDValue Add2; 1011 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) { 1012 ConstantSDNode *ConstOp; 1013 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 1014 ConstOp->isOne()) { 1015 ExtOpA = Op1; 1016 ExtOpB = Op3; 1017 Add2 = A; 1018 return true; 1019 } 1020 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 1021 ConstOp->isOne()) { 1022 ExtOpA = Op1; 1023 ExtOpB = Op2; 1024 Add2 = A; 1025 return true; 1026 } 1027 return false; 1028 }; 1029 bool IsCeil = 1030 (ExtOpA.getOpcode() == ISD::ADD && 1031 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) || 1032 (ExtOpB.getOpcode() == ISD::ADD && 1033 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB)); 1034 1035 // If the shift is signed (sra): 1036 // - Needs >= 2 sign bit for both operands. 1037 // - Needs >= 2 zero bits. 1038 // If the shift is unsigned (srl): 1039 // - Needs >= 1 zero bit for both operands. 1040 // - Needs 1 demanded bit zero and >= 2 sign bits. 1041 SelectionDAG &DAG = TLO.DAG; 1042 unsigned ShiftOpc = Op.getOpcode(); 1043 bool IsSigned = false; 1044 unsigned KnownBits; 1045 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 1046 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 1047 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 1048 unsigned NumZeroA = 1049 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 1050 unsigned NumZeroB = 1051 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 1052 unsigned NumZero = std::min(NumZeroA, NumZeroB); 1053 1054 switch (ShiftOpc) { 1055 default: 1056 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 1057 case ISD::SRA: { 1058 if (NumZero >= 2 && NumSigned < NumZero) { 1059 IsSigned = false; 1060 KnownBits = NumZero; 1061 break; 1062 } 1063 if (NumSigned >= 1) { 1064 IsSigned = true; 1065 KnownBits = NumSigned; 1066 break; 1067 } 1068 return SDValue(); 1069 } 1070 case ISD::SRL: { 1071 if (NumZero >= 1 && NumSigned < NumZero) { 1072 IsSigned = false; 1073 KnownBits = NumZero; 1074 break; 1075 } 1076 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1077 IsSigned = true; 1078 KnownBits = NumSigned; 1079 break; 1080 } 1081 return SDValue(); 1082 } 1083 } 1084 1085 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1086 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1087 1088 // Find the smallest power-2 type that is legal for this vector size and 1089 // operation, given the original type size and the number of known sign/zero 1090 // bits. 1091 EVT VT = Op.getValueType(); 1092 unsigned MinWidth = 1093 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1094 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth)); 1095 if (NVT.getScalarSizeInBits() > VT.getScalarSizeInBits()) 1096 return SDValue(); 1097 if (VT.isVector()) 1098 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1099 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) { 1100 // If we could not transform, and (both) adds are nuw/nsw, we can use the 1101 // larger type size to do the transform. 1102 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT)) 1103 return SDValue(); 1104 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0), 1105 Add.getOperand(1)) && 1106 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0), 1107 Add2.getOperand(1)))) 1108 NVT = VT; 1109 else 1110 return SDValue(); 1111 } 1112 1113 // Don't create a AVGFLOOR node with a scalar constant unless its legal as 1114 // this is likely to stop other folds (reassociation, value tracking etc.) 1115 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) && 1116 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB))) 1117 return SDValue(); 1118 1119 SDLoc DL(Op); 1120 SDValue ResultAVG = 1121 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT), 1122 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT)); 1123 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT); 1124 } 1125 1126 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1127 /// result of Op are ever used downstream. If we can use this information to 1128 /// simplify Op, create a new simplified DAG node and return true, returning the 1129 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1130 /// return a mask of Known bits for the expression (used to simplify the 1131 /// caller). The Known bits may only be accurate for those bits in the 1132 /// OriginalDemandedBits and OriginalDemandedElts. 1133 bool TargetLowering::SimplifyDemandedBits( 1134 SDValue Op, const APInt &OriginalDemandedBits, 1135 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1136 unsigned Depth, bool AssumeSingleUse) const { 1137 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1138 assert(Op.getScalarValueSizeInBits() == BitWidth && 1139 "Mask size mismatches value type size!"); 1140 1141 // Don't know anything. 1142 Known = KnownBits(BitWidth); 1143 1144 EVT VT = Op.getValueType(); 1145 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1146 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1147 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) && 1148 "Unexpected vector size"); 1149 1150 APInt DemandedBits = OriginalDemandedBits; 1151 APInt DemandedElts = OriginalDemandedElts; 1152 SDLoc dl(Op); 1153 1154 // Undef operand. 1155 if (Op.isUndef()) 1156 return false; 1157 1158 // We can't simplify target constants. 1159 if (Op.getOpcode() == ISD::TargetConstant) 1160 return false; 1161 1162 if (Op.getOpcode() == ISD::Constant) { 1163 // We know all of the bits for a constant! 1164 Known = KnownBits::makeConstant(Op->getAsAPIntVal()); 1165 return false; 1166 } 1167 1168 if (Op.getOpcode() == ISD::ConstantFP) { 1169 // We know all of the bits for a floating point constant! 1170 Known = KnownBits::makeConstant( 1171 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1172 return false; 1173 } 1174 1175 // Other users may use these bits. 1176 bool HasMultiUse = false; 1177 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) { 1178 if (Depth >= SelectionDAG::MaxRecursionDepth) { 1179 // Limit search depth. 1180 return false; 1181 } 1182 // Allow multiple uses, just set the DemandedBits/Elts to all bits. 1183 DemandedBits = APInt::getAllOnes(BitWidth); 1184 DemandedElts = APInt::getAllOnes(NumElts); 1185 HasMultiUse = true; 1186 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1187 // Not demanding any bits/elts from Op. 1188 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1189 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1190 // Limit search depth. 1191 return false; 1192 } 1193 1194 KnownBits Known2; 1195 switch (Op.getOpcode()) { 1196 case ISD::SCALAR_TO_VECTOR: { 1197 if (VT.isScalableVector()) 1198 return false; 1199 if (!DemandedElts[0]) 1200 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1201 1202 KnownBits SrcKnown; 1203 SDValue Src = Op.getOperand(0); 1204 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1205 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1206 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1207 return true; 1208 1209 // Upper elements are undef, so only get the knownbits if we just demand 1210 // the bottom element. 1211 if (DemandedElts == 1) 1212 Known = SrcKnown.anyextOrTrunc(BitWidth); 1213 break; 1214 } 1215 case ISD::BUILD_VECTOR: 1216 // Collect the known bits that are shared by every demanded element. 1217 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1218 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1219 return false; // Don't fall through, will infinitely loop. 1220 case ISD::SPLAT_VECTOR: { 1221 SDValue Scl = Op.getOperand(0); 1222 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits()); 1223 KnownBits KnownScl; 1224 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1225 return true; 1226 1227 // Implicitly truncate the bits to match the official semantics of 1228 // SPLAT_VECTOR. 1229 Known = KnownScl.trunc(BitWidth); 1230 break; 1231 } 1232 case ISD::LOAD: { 1233 auto *LD = cast<LoadSDNode>(Op); 1234 if (getTargetConstantFromLoad(LD)) { 1235 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1236 return false; // Don't fall through, will infinitely loop. 1237 } 1238 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1239 // If this is a ZEXTLoad and we are looking at the loaded value. 1240 EVT MemVT = LD->getMemoryVT(); 1241 unsigned MemBits = MemVT.getScalarSizeInBits(); 1242 Known.Zero.setBitsFrom(MemBits); 1243 return false; // Don't fall through, will infinitely loop. 1244 } 1245 break; 1246 } 1247 case ISD::INSERT_VECTOR_ELT: { 1248 if (VT.isScalableVector()) 1249 return false; 1250 SDValue Vec = Op.getOperand(0); 1251 SDValue Scl = Op.getOperand(1); 1252 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1253 EVT VecVT = Vec.getValueType(); 1254 1255 // If index isn't constant, assume we need all vector elements AND the 1256 // inserted element. 1257 APInt DemandedVecElts(DemandedElts); 1258 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1259 unsigned Idx = CIdx->getZExtValue(); 1260 DemandedVecElts.clearBit(Idx); 1261 1262 // Inserted element is not required. 1263 if (!DemandedElts[Idx]) 1264 return TLO.CombineTo(Op, Vec); 1265 } 1266 1267 KnownBits KnownScl; 1268 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1269 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1270 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1271 return true; 1272 1273 Known = KnownScl.anyextOrTrunc(BitWidth); 1274 1275 KnownBits KnownVec; 1276 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1277 Depth + 1)) 1278 return true; 1279 1280 if (!!DemandedVecElts) 1281 Known = Known.intersectWith(KnownVec); 1282 1283 return false; 1284 } 1285 case ISD::INSERT_SUBVECTOR: { 1286 if (VT.isScalableVector()) 1287 return false; 1288 // Demand any elements from the subvector and the remainder from the src its 1289 // inserted into. 1290 SDValue Src = Op.getOperand(0); 1291 SDValue Sub = Op.getOperand(1); 1292 uint64_t Idx = Op.getConstantOperandVal(2); 1293 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1294 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1295 APInt DemandedSrcElts = DemandedElts; 1296 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1297 1298 KnownBits KnownSub, KnownSrc; 1299 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1300 Depth + 1)) 1301 return true; 1302 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1303 Depth + 1)) 1304 return true; 1305 1306 Known.Zero.setAllBits(); 1307 Known.One.setAllBits(); 1308 if (!!DemandedSubElts) 1309 Known = Known.intersectWith(KnownSub); 1310 if (!!DemandedSrcElts) 1311 Known = Known.intersectWith(KnownSrc); 1312 1313 // Attempt to avoid multi-use src if we don't need anything from it. 1314 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1315 !DemandedSrcElts.isAllOnes()) { 1316 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1317 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1318 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1319 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1320 if (NewSub || NewSrc) { 1321 NewSub = NewSub ? NewSub : Sub; 1322 NewSrc = NewSrc ? NewSrc : Src; 1323 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1324 Op.getOperand(2)); 1325 return TLO.CombineTo(Op, NewOp); 1326 } 1327 } 1328 break; 1329 } 1330 case ISD::EXTRACT_SUBVECTOR: { 1331 if (VT.isScalableVector()) 1332 return false; 1333 // Offset the demanded elts by the subvector index. 1334 SDValue Src = Op.getOperand(0); 1335 if (Src.getValueType().isScalableVector()) 1336 break; 1337 uint64_t Idx = Op.getConstantOperandVal(1); 1338 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1339 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1340 1341 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1342 Depth + 1)) 1343 return true; 1344 1345 // Attempt to avoid multi-use src if we don't need anything from it. 1346 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1347 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1348 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1349 if (DemandedSrc) { 1350 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1351 Op.getOperand(1)); 1352 return TLO.CombineTo(Op, NewOp); 1353 } 1354 } 1355 break; 1356 } 1357 case ISD::CONCAT_VECTORS: { 1358 if (VT.isScalableVector()) 1359 return false; 1360 Known.Zero.setAllBits(); 1361 Known.One.setAllBits(); 1362 EVT SubVT = Op.getOperand(0).getValueType(); 1363 unsigned NumSubVecs = Op.getNumOperands(); 1364 unsigned NumSubElts = SubVT.getVectorNumElements(); 1365 for (unsigned i = 0; i != NumSubVecs; ++i) { 1366 APInt DemandedSubElts = 1367 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1368 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1369 Known2, TLO, Depth + 1)) 1370 return true; 1371 // Known bits are shared by every demanded subvector element. 1372 if (!!DemandedSubElts) 1373 Known = Known.intersectWith(Known2); 1374 } 1375 break; 1376 } 1377 case ISD::VECTOR_SHUFFLE: { 1378 assert(!VT.isScalableVector()); 1379 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1380 1381 // Collect demanded elements from shuffle operands.. 1382 APInt DemandedLHS, DemandedRHS; 1383 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS, 1384 DemandedRHS)) 1385 break; 1386 1387 if (!!DemandedLHS || !!DemandedRHS) { 1388 SDValue Op0 = Op.getOperand(0); 1389 SDValue Op1 = Op.getOperand(1); 1390 1391 Known.Zero.setAllBits(); 1392 Known.One.setAllBits(); 1393 if (!!DemandedLHS) { 1394 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1395 Depth + 1)) 1396 return true; 1397 Known = Known.intersectWith(Known2); 1398 } 1399 if (!!DemandedRHS) { 1400 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1401 Depth + 1)) 1402 return true; 1403 Known = Known.intersectWith(Known2); 1404 } 1405 1406 // Attempt to avoid multi-use ops if we don't need anything from them. 1407 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1408 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1409 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1410 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1411 if (DemandedOp0 || DemandedOp1) { 1412 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1413 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1414 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1415 return TLO.CombineTo(Op, NewOp); 1416 } 1417 } 1418 break; 1419 } 1420 case ISD::AND: { 1421 SDValue Op0 = Op.getOperand(0); 1422 SDValue Op1 = Op.getOperand(1); 1423 1424 // If the RHS is a constant, check to see if the LHS would be zero without 1425 // using the bits from the RHS. Below, we use knowledge about the RHS to 1426 // simplify the LHS, here we're using information from the LHS to simplify 1427 // the RHS. 1428 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) { 1429 // Do not increment Depth here; that can cause an infinite loop. 1430 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1431 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1432 if ((LHSKnown.Zero & DemandedBits) == 1433 (~RHSC->getAPIntValue() & DemandedBits)) 1434 return TLO.CombineTo(Op, Op0); 1435 1436 // If any of the set bits in the RHS are known zero on the LHS, shrink 1437 // the constant. 1438 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1439 DemandedElts, TLO)) 1440 return true; 1441 1442 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1443 // constant, but if this 'and' is only clearing bits that were just set by 1444 // the xor, then this 'and' can be eliminated by shrinking the mask of 1445 // the xor. For example, for a 32-bit X: 1446 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1447 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1448 LHSKnown.One == ~RHSC->getAPIntValue()) { 1449 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1450 return TLO.CombineTo(Op, Xor); 1451 } 1452 } 1453 1454 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1455 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1456 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() && 1457 (Op0.getOperand(0).isUndef() || 1458 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1459 Op0->hasOneUse()) { 1460 unsigned NumSubElts = 1461 Op0.getOperand(1).getValueType().getVectorNumElements(); 1462 unsigned SubIdx = Op0.getConstantOperandVal(2); 1463 APInt DemandedSub = 1464 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1465 KnownBits KnownSubMask = 1466 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1467 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1468 SDValue NewAnd = 1469 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1470 SDValue NewInsert = 1471 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1472 Op0.getOperand(1), Op0.getOperand(2)); 1473 return TLO.CombineTo(Op, NewInsert); 1474 } 1475 } 1476 1477 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1478 Depth + 1)) 1479 return true; 1480 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1481 Known2, TLO, Depth + 1)) 1482 return true; 1483 1484 // If all of the demanded bits are known one on one side, return the other. 1485 // These bits cannot contribute to the result of the 'and'. 1486 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1487 return TLO.CombineTo(Op, Op0); 1488 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1489 return TLO.CombineTo(Op, Op1); 1490 // If all of the demanded bits in the inputs are known zeros, return zero. 1491 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1492 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1493 // If the RHS is a constant, see if we can simplify it. 1494 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1495 TLO)) 1496 return true; 1497 // If the operation can be done in a smaller type, do so. 1498 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1499 return true; 1500 1501 // Attempt to avoid multi-use ops if we don't need anything from them. 1502 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1503 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1504 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1505 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1506 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1507 if (DemandedOp0 || DemandedOp1) { 1508 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1509 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1510 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1511 return TLO.CombineTo(Op, NewOp); 1512 } 1513 } 1514 1515 Known &= Known2; 1516 break; 1517 } 1518 case ISD::OR: { 1519 SDValue Op0 = Op.getOperand(0); 1520 SDValue Op1 = Op.getOperand(1); 1521 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1522 Depth + 1)) { 1523 Op->dropFlags(SDNodeFlags::Disjoint); 1524 return true; 1525 } 1526 1527 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1528 Known2, TLO, Depth + 1)) { 1529 Op->dropFlags(SDNodeFlags::Disjoint); 1530 return true; 1531 } 1532 1533 // If all of the demanded bits are known zero on one side, return the other. 1534 // These bits cannot contribute to the result of the 'or'. 1535 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1536 return TLO.CombineTo(Op, Op0); 1537 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1538 return TLO.CombineTo(Op, Op1); 1539 // If the RHS is a constant, see if we can simplify it. 1540 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1541 return true; 1542 // If the operation can be done in a smaller type, do so. 1543 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1544 return true; 1545 1546 // Attempt to avoid multi-use ops if we don't need anything from them. 1547 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1548 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1549 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1550 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1551 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1552 if (DemandedOp0 || DemandedOp1) { 1553 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1554 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1555 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1556 return TLO.CombineTo(Op, NewOp); 1557 } 1558 } 1559 1560 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2)) 1561 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks. 1562 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND && 1563 Op0->hasOneUse() && Op1->hasOneUse()) { 1564 // Attempt to match all commutations - m_c_Or would've been useful! 1565 for (int I = 0; I != 2; ++I) { 1566 SDValue X = Op.getOperand(I).getOperand(0); 1567 SDValue C1 = Op.getOperand(I).getOperand(1); 1568 SDValue Alt = Op.getOperand(1 - I).getOperand(0); 1569 SDValue C2 = Op.getOperand(1 - I).getOperand(1); 1570 if (Alt.getOpcode() == ISD::OR) { 1571 for (int J = 0; J != 2; ++J) { 1572 if (X == Alt.getOperand(J)) { 1573 SDValue Y = Alt.getOperand(1 - J); 1574 if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, 1575 {C1, C2})) { 1576 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12); 1577 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2); 1578 return TLO.CombineTo( 1579 Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY)); 1580 } 1581 } 1582 } 1583 } 1584 } 1585 } 1586 1587 Known |= Known2; 1588 break; 1589 } 1590 case ISD::XOR: { 1591 SDValue Op0 = Op.getOperand(0); 1592 SDValue Op1 = Op.getOperand(1); 1593 1594 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1595 Depth + 1)) 1596 return true; 1597 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1598 Depth + 1)) 1599 return true; 1600 1601 // If all of the demanded bits are known zero on one side, return the other. 1602 // These bits cannot contribute to the result of the 'xor'. 1603 if (DemandedBits.isSubsetOf(Known.Zero)) 1604 return TLO.CombineTo(Op, Op0); 1605 if (DemandedBits.isSubsetOf(Known2.Zero)) 1606 return TLO.CombineTo(Op, Op1); 1607 // If the operation can be done in a smaller type, do so. 1608 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1609 return true; 1610 1611 // If all of the unknown bits are known to be zero on one side or the other 1612 // turn this into an *inclusive* or. 1613 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1614 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1615 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1616 1617 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts); 1618 if (C) { 1619 // If one side is a constant, and all of the set bits in the constant are 1620 // also known set on the other side, turn this into an AND, as we know 1621 // the bits will be cleared. 1622 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1623 // NB: it is okay if more bits are known than are requested 1624 if (C->getAPIntValue() == Known2.One) { 1625 SDValue ANDC = 1626 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1627 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1628 } 1629 1630 // If the RHS is a constant, see if we can change it. Don't alter a -1 1631 // constant because that's a 'not' op, and that is better for combining 1632 // and codegen. 1633 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1634 // We're flipping all demanded bits. Flip the undemanded bits too. 1635 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1636 return TLO.CombineTo(Op, New); 1637 } 1638 1639 unsigned Op0Opcode = Op0.getOpcode(); 1640 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) { 1641 if (ConstantSDNode *ShiftC = 1642 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) { 1643 // Don't crash on an oversized shift. We can not guarantee that a 1644 // bogus shift has been simplified to undef. 1645 if (ShiftC->getAPIntValue().ult(BitWidth)) { 1646 uint64_t ShiftAmt = ShiftC->getZExtValue(); 1647 APInt Ones = APInt::getAllOnes(BitWidth); 1648 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) 1649 : Ones.lshr(ShiftAmt); 1650 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) && 1651 isDesirableToCommuteXorWithShift(Op.getNode())) { 1652 // If the xor constant is a demanded mask, do a 'not' before the 1653 // shift: 1654 // xor (X << ShiftC), XorC --> (not X) << ShiftC 1655 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 1656 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT); 1657 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not, 1658 Op0.getOperand(1))); 1659 } 1660 } 1661 } 1662 } 1663 } 1664 1665 // If we can't turn this into a 'not', try to shrink the constant. 1666 if (!C || !C->isAllOnes()) 1667 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1668 return true; 1669 1670 // Attempt to avoid multi-use ops if we don't need anything from them. 1671 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1672 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1673 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1674 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1675 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1676 if (DemandedOp0 || DemandedOp1) { 1677 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1678 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1679 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1680 return TLO.CombineTo(Op, NewOp); 1681 } 1682 } 1683 1684 Known ^= Known2; 1685 break; 1686 } 1687 case ISD::SELECT: 1688 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1689 Known, TLO, Depth + 1)) 1690 return true; 1691 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1692 Known2, TLO, Depth + 1)) 1693 return true; 1694 1695 // If the operands are constants, see if we can simplify them. 1696 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1697 return true; 1698 1699 // Only known if known in both the LHS and RHS. 1700 Known = Known.intersectWith(Known2); 1701 break; 1702 case ISD::VSELECT: 1703 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1704 Known, TLO, Depth + 1)) 1705 return true; 1706 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1707 Known2, TLO, Depth + 1)) 1708 return true; 1709 1710 // Only known if known in both the LHS and RHS. 1711 Known = Known.intersectWith(Known2); 1712 break; 1713 case ISD::SELECT_CC: 1714 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts, 1715 Known, TLO, Depth + 1)) 1716 return true; 1717 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1718 Known2, TLO, Depth + 1)) 1719 return true; 1720 1721 // If the operands are constants, see if we can simplify them. 1722 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1723 return true; 1724 1725 // Only known if known in both the LHS and RHS. 1726 Known = Known.intersectWith(Known2); 1727 break; 1728 case ISD::SETCC: { 1729 SDValue Op0 = Op.getOperand(0); 1730 SDValue Op1 = Op.getOperand(1); 1731 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1732 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1733 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1734 // -1, we may be able to bypass the setcc. 1735 if (DemandedBits.isSignMask() && 1736 Op0.getScalarValueSizeInBits() == BitWidth && 1737 getBooleanContents(Op0.getValueType()) == 1738 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1739 // If we're testing X < 0, then this compare isn't needed - just use X! 1740 // FIXME: We're limiting to integer types here, but this should also work 1741 // if we don't care about FP signed-zero. The use of SETLT with FP means 1742 // that we don't care about NaNs. 1743 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1744 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1745 return TLO.CombineTo(Op, Op0); 1746 1747 // TODO: Should we check for other forms of sign-bit comparisons? 1748 // Examples: X <= -1, X >= 0 1749 } 1750 if (getBooleanContents(Op0.getValueType()) == 1751 TargetLowering::ZeroOrOneBooleanContent && 1752 BitWidth > 1) 1753 Known.Zero.setBitsFrom(1); 1754 break; 1755 } 1756 case ISD::SHL: { 1757 SDValue Op0 = Op.getOperand(0); 1758 SDValue Op1 = Op.getOperand(1); 1759 EVT ShiftVT = Op1.getValueType(); 1760 1761 if (std::optional<uint64_t> KnownSA = 1762 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 1763 unsigned ShAmt = *KnownSA; 1764 if (ShAmt == 0) 1765 return TLO.CombineTo(Op, Op0); 1766 1767 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1768 // single shift. We can do this if the bottom bits (which are shifted 1769 // out) are never demanded. 1770 // TODO - support non-uniform vector amounts. 1771 if (Op0.getOpcode() == ISD::SRL) { 1772 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1773 if (std::optional<uint64_t> InnerSA = 1774 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1775 unsigned C1 = *InnerSA; 1776 unsigned Opc = ISD::SHL; 1777 int Diff = ShAmt - C1; 1778 if (Diff < 0) { 1779 Diff = -Diff; 1780 Opc = ISD::SRL; 1781 } 1782 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1783 return TLO.CombineTo( 1784 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1785 } 1786 } 1787 } 1788 1789 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1790 // are not demanded. This will likely allow the anyext to be folded away. 1791 // TODO - support non-uniform vector amounts. 1792 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1793 SDValue InnerOp = Op0.getOperand(0); 1794 EVT InnerVT = InnerOp.getValueType(); 1795 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1796 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1797 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1798 SDValue NarrowShl = TLO.DAG.getNode( 1799 ISD::SHL, dl, InnerVT, InnerOp, 1800 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl)); 1801 return TLO.CombineTo( 1802 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1803 } 1804 1805 // Repeat the SHL optimization above in cases where an extension 1806 // intervenes: (shl (anyext (shr x, c1)), c2) to 1807 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1808 // aren't demanded (as above) and that the shifted upper c1 bits of 1809 // x aren't demanded. 1810 // TODO - support non-uniform vector amounts. 1811 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() && 1812 InnerOp.hasOneUse()) { 1813 if (std::optional<uint64_t> SA2 = TLO.DAG.getValidShiftAmount( 1814 InnerOp, DemandedElts, Depth + 2)) { 1815 unsigned InnerShAmt = *SA2; 1816 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1817 DemandedBits.getActiveBits() <= 1818 (InnerBits - InnerShAmt + ShAmt) && 1819 DemandedBits.countr_zero() >= ShAmt) { 1820 SDValue NewSA = 1821 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1822 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1823 InnerOp.getOperand(0)); 1824 return TLO.CombineTo( 1825 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1826 } 1827 } 1828 } 1829 } 1830 1831 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1832 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1833 Depth + 1)) { 1834 // Disable the nsw and nuw flags. We can no longer guarantee that we 1835 // won't wrap after simplification. 1836 Op->dropFlags(SDNodeFlags::NoWrap); 1837 return true; 1838 } 1839 Known.Zero <<= ShAmt; 1840 Known.One <<= ShAmt; 1841 // low bits known zero. 1842 Known.Zero.setLowBits(ShAmt); 1843 1844 // Attempt to avoid multi-use ops if we don't need anything from them. 1845 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1846 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1847 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1848 if (DemandedOp0) { 1849 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1850 return TLO.CombineTo(Op, NewOp); 1851 } 1852 } 1853 1854 // TODO: Can we merge this fold with the one below? 1855 // Try shrinking the operation as long as the shift amount will still be 1856 // in range. 1857 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() && 1858 Op.getNode()->hasOneUse()) { 1859 // Search for the smallest integer type with free casts to and from 1860 // Op's type. For expedience, just check power-of-2 integer types. 1861 unsigned DemandedSize = DemandedBits.getActiveBits(); 1862 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize); 1863 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 1864 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits); 1865 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) && 1866 isTypeDesirableForOp(ISD::SHL, SmallVT) && 1867 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) && 1868 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) { 1869 assert(DemandedSize <= SmallVTBits && 1870 "Narrowed below demanded bits?"); 1871 // We found a type with free casts. 1872 SDValue NarrowShl = TLO.DAG.getNode( 1873 ISD::SHL, dl, SmallVT, 1874 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 1875 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl)); 1876 return TLO.CombineTo( 1877 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1878 } 1879 } 1880 } 1881 1882 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1883 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K)) 1884 // Only do this if we demand the upper half so the knownbits are correct. 1885 unsigned HalfWidth = BitWidth / 2; 1886 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth && 1887 DemandedBits.countLeadingOnes() >= HalfWidth) { 1888 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth); 1889 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) && 1890 isTypeDesirableForOp(ISD::SHL, HalfVT) && 1891 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 1892 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) { 1893 // If we're demanding the upper bits at all, we must ensure 1894 // that the upper bits of the shift result are known to be zero, 1895 // which is equivalent to the narrow shift being NUW. 1896 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) { 1897 bool IsNSW = Known.countMinSignBits() > HalfWidth; 1898 SDNodeFlags Flags; 1899 Flags.setNoSignedWrap(IsNSW); 1900 Flags.setNoUnsignedWrap(IsNUW); 1901 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 1902 SDValue NewShiftAmt = 1903 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl); 1904 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp, 1905 NewShiftAmt, Flags); 1906 SDValue NewExt = 1907 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift); 1908 return TLO.CombineTo(Op, NewExt); 1909 } 1910 } 1911 } 1912 } else { 1913 // This is a variable shift, so we can't shift the demand mask by a known 1914 // amount. But if we are not demanding high bits, then we are not 1915 // demanding those bits from the pre-shifted operand either. 1916 if (unsigned CTLZ = DemandedBits.countl_zero()) { 1917 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1918 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1919 Depth + 1)) { 1920 // Disable the nsw and nuw flags. We can no longer guarantee that we 1921 // won't wrap after simplification. 1922 Op->dropFlags(SDNodeFlags::NoWrap); 1923 return true; 1924 } 1925 Known.resetAll(); 1926 } 1927 } 1928 1929 // If we are only demanding sign bits then we can use the shift source 1930 // directly. 1931 if (std::optional<uint64_t> MaxSA = 1932 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 1933 unsigned ShAmt = *MaxSA; 1934 unsigned NumSignBits = 1935 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1936 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 1937 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1938 return TLO.CombineTo(Op, Op0); 1939 } 1940 break; 1941 } 1942 case ISD::SRL: { 1943 SDValue Op0 = Op.getOperand(0); 1944 SDValue Op1 = Op.getOperand(1); 1945 EVT ShiftVT = Op1.getValueType(); 1946 1947 if (std::optional<uint64_t> KnownSA = 1948 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 1949 unsigned ShAmt = *KnownSA; 1950 if (ShAmt == 0) 1951 return TLO.CombineTo(Op, Op0); 1952 1953 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1954 // single shift. We can do this if the top bits (which are shifted out) 1955 // are never demanded. 1956 // TODO - support non-uniform vector amounts. 1957 if (Op0.getOpcode() == ISD::SHL) { 1958 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1959 if (std::optional<uint64_t> InnerSA = 1960 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1961 unsigned C1 = *InnerSA; 1962 unsigned Opc = ISD::SRL; 1963 int Diff = ShAmt - C1; 1964 if (Diff < 0) { 1965 Diff = -Diff; 1966 Opc = ISD::SHL; 1967 } 1968 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1969 return TLO.CombineTo( 1970 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1971 } 1972 } 1973 } 1974 1975 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a 1976 // single sra. We can do this if the top bits are never demanded. 1977 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) { 1978 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1979 if (std::optional<uint64_t> InnerSA = 1980 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1981 unsigned C1 = *InnerSA; 1982 // Clamp the combined shift amount if it exceeds the bit width. 1983 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1); 1984 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT); 1985 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT, 1986 Op0.getOperand(0), NewSA)); 1987 } 1988 } 1989 } 1990 1991 APInt InDemandedMask = (DemandedBits << ShAmt); 1992 1993 // If the shift is exact, then it does demand the low bits (and knows that 1994 // they are zero). 1995 if (Op->getFlags().hasExact()) 1996 InDemandedMask.setLowBits(ShAmt); 1997 1998 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1999 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K)) 2000 if ((BitWidth % 2) == 0 && !VT.isVector()) { 2001 APInt HiBits = APInt::getHighBitsSet(BitWidth, BitWidth / 2); 2002 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2); 2003 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) && 2004 isTypeDesirableForOp(ISD::SRL, HalfVT) && 2005 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 2006 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) && 2007 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) || 2008 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) { 2009 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 2010 SDValue NewShiftAmt = 2011 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl); 2012 SDValue NewShift = 2013 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt); 2014 return TLO.CombineTo( 2015 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift)); 2016 } 2017 } 2018 2019 // Compute the new bits that are at the top now. 2020 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 2021 Depth + 1)) 2022 return true; 2023 Known.Zero.lshrInPlace(ShAmt); 2024 Known.One.lshrInPlace(ShAmt); 2025 // High bits known zero. 2026 Known.Zero.setHighBits(ShAmt); 2027 2028 // Attempt to avoid multi-use ops if we don't need anything from them. 2029 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2030 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2031 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 2032 if (DemandedOp0) { 2033 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1); 2034 return TLO.CombineTo(Op, NewOp); 2035 } 2036 } 2037 } else { 2038 // Use generic knownbits computation as it has support for non-uniform 2039 // shift amounts. 2040 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2041 } 2042 2043 // If we are only demanding sign bits then we can use the shift source 2044 // directly. 2045 if (std::optional<uint64_t> MaxSA = 2046 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 2047 unsigned ShAmt = *MaxSA; 2048 // Must already be signbits in DemandedBits bounds, and can't demand any 2049 // shifted in zeroes. 2050 if (DemandedBits.countl_zero() >= ShAmt) { 2051 unsigned NumSignBits = 2052 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 2053 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits)) 2054 return TLO.CombineTo(Op, Op0); 2055 } 2056 } 2057 2058 // Try to match AVG patterns (after shift simplification). 2059 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits, 2060 DemandedElts, Depth + 1)) 2061 return TLO.CombineTo(Op, AVG); 2062 2063 break; 2064 } 2065 case ISD::SRA: { 2066 SDValue Op0 = Op.getOperand(0); 2067 SDValue Op1 = Op.getOperand(1); 2068 EVT ShiftVT = Op1.getValueType(); 2069 2070 // If we only want bits that already match the signbit then we don't need 2071 // to shift. 2072 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero(); 2073 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 2074 NumHiDemandedBits) 2075 return TLO.CombineTo(Op, Op0); 2076 2077 // If this is an arithmetic shift right and only the low-bit is set, we can 2078 // always convert this into a logical shr, even if the shift amount is 2079 // variable. The low bit of the shift cannot be an input sign bit unless 2080 // the shift amount is >= the size of the datatype, which is undefined. 2081 if (DemandedBits.isOne()) 2082 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2083 2084 if (std::optional<uint64_t> KnownSA = 2085 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 2086 unsigned ShAmt = *KnownSA; 2087 if (ShAmt == 0) 2088 return TLO.CombineTo(Op, Op0); 2089 2090 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target 2091 // supports sext_inreg. 2092 if (Op0.getOpcode() == ISD::SHL) { 2093 if (std::optional<uint64_t> InnerSA = 2094 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 2095 unsigned LowBits = BitWidth - ShAmt; 2096 EVT ExtVT = EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits); 2097 if (VT.isVector()) 2098 ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtVT, 2099 VT.getVectorElementCount()); 2100 2101 if (*InnerSA == ShAmt) { 2102 if (!TLO.LegalOperations() || 2103 getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == Legal) 2104 return TLO.CombineTo( 2105 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, 2106 Op0.getOperand(0), 2107 TLO.DAG.getValueType(ExtVT))); 2108 2109 // Even if we can't convert to sext_inreg, we might be able to 2110 // remove this shift pair if the input is already sign extended. 2111 unsigned NumSignBits = 2112 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts); 2113 if (NumSignBits > ShAmt) 2114 return TLO.CombineTo(Op, Op0.getOperand(0)); 2115 } 2116 } 2117 } 2118 2119 APInt InDemandedMask = (DemandedBits << ShAmt); 2120 2121 // If the shift is exact, then it does demand the low bits (and knows that 2122 // they are zero). 2123 if (Op->getFlags().hasExact()) 2124 InDemandedMask.setLowBits(ShAmt); 2125 2126 // If any of the demanded bits are produced by the sign extension, we also 2127 // demand the input sign bit. 2128 if (DemandedBits.countl_zero() < ShAmt) 2129 InDemandedMask.setSignBit(); 2130 2131 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 2132 Depth + 1)) 2133 return true; 2134 Known.Zero.lshrInPlace(ShAmt); 2135 Known.One.lshrInPlace(ShAmt); 2136 2137 // If the input sign bit is known to be zero, or if none of the top bits 2138 // are demanded, turn this into an unsigned shift right. 2139 if (Known.Zero[BitWidth - ShAmt - 1] || 2140 DemandedBits.countl_zero() >= ShAmt) { 2141 SDNodeFlags Flags; 2142 Flags.setExact(Op->getFlags().hasExact()); 2143 return TLO.CombineTo( 2144 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 2145 } 2146 2147 int Log2 = DemandedBits.exactLogBase2(); 2148 if (Log2 >= 0) { 2149 // The bit must come from the sign. 2150 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 2151 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 2152 } 2153 2154 if (Known.One[BitWidth - ShAmt - 1]) 2155 // New bits are known one. 2156 Known.One.setHighBits(ShAmt); 2157 2158 // Attempt to avoid multi-use ops if we don't need anything from them. 2159 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2160 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2161 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 2162 if (DemandedOp0) { 2163 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 2164 return TLO.CombineTo(Op, NewOp); 2165 } 2166 } 2167 } 2168 2169 // Try to match AVG patterns (after shift simplification). 2170 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits, 2171 DemandedElts, Depth + 1)) 2172 return TLO.CombineTo(Op, AVG); 2173 2174 break; 2175 } 2176 case ISD::FSHL: 2177 case ISD::FSHR: { 2178 SDValue Op0 = Op.getOperand(0); 2179 SDValue Op1 = Op.getOperand(1); 2180 SDValue Op2 = Op.getOperand(2); 2181 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 2182 2183 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 2184 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2185 2186 // For fshl, 0-shift returns the 1st arg. 2187 // For fshr, 0-shift returns the 2nd arg. 2188 if (Amt == 0) { 2189 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 2190 Known, TLO, Depth + 1)) 2191 return true; 2192 break; 2193 } 2194 2195 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 2196 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 2197 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 2198 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 2199 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2200 Depth + 1)) 2201 return true; 2202 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 2203 Depth + 1)) 2204 return true; 2205 2206 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2207 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2208 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2209 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2210 Known = Known.unionWith(Known2); 2211 2212 // Attempt to avoid multi-use ops if we don't need anything from them. 2213 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 2214 !DemandedElts.isAllOnes()) { 2215 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2216 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 2217 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2218 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 2219 if (DemandedOp0 || DemandedOp1) { 2220 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 2221 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 2222 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 2223 DemandedOp1, Op2); 2224 return TLO.CombineTo(Op, NewOp); 2225 } 2226 } 2227 } 2228 2229 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2230 if (isPowerOf2_32(BitWidth)) { 2231 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 2232 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 2233 Known2, TLO, Depth + 1)) 2234 return true; 2235 } 2236 break; 2237 } 2238 case ISD::ROTL: 2239 case ISD::ROTR: { 2240 SDValue Op0 = Op.getOperand(0); 2241 SDValue Op1 = Op.getOperand(1); 2242 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 2243 2244 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 2245 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 2246 return TLO.CombineTo(Op, Op0); 2247 2248 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 2249 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2250 unsigned RevAmt = BitWidth - Amt; 2251 2252 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 2253 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 2254 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 2255 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2256 Depth + 1)) 2257 return true; 2258 2259 // rot*(x, 0) --> x 2260 if (Amt == 0) 2261 return TLO.CombineTo(Op, Op0); 2262 2263 // See if we don't demand either half of the rotated bits. 2264 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 2265 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) { 2266 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 2267 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 2268 } 2269 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 2270 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) { 2271 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 2272 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2273 } 2274 } 2275 2276 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2277 if (isPowerOf2_32(BitWidth)) { 2278 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2279 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2280 Depth + 1)) 2281 return true; 2282 } 2283 break; 2284 } 2285 case ISD::SMIN: 2286 case ISD::SMAX: 2287 case ISD::UMIN: 2288 case ISD::UMAX: { 2289 unsigned Opc = Op.getOpcode(); 2290 SDValue Op0 = Op.getOperand(0); 2291 SDValue Op1 = Op.getOperand(1); 2292 2293 // If we're only demanding signbits, then we can simplify to OR/AND node. 2294 unsigned BitOp = 2295 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND; 2296 unsigned NumSignBits = 2297 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1), 2298 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1)); 2299 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero(); 2300 if (NumSignBits >= NumDemandedUpperBits) 2301 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1)); 2302 2303 // Check if one arg is always less/greater than (or equal) to the other arg. 2304 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2305 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2306 switch (Opc) { 2307 case ISD::SMIN: 2308 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1)) 2309 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1); 2310 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1)) 2311 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1); 2312 Known = KnownBits::smin(Known0, Known1); 2313 break; 2314 case ISD::SMAX: 2315 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1)) 2316 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1); 2317 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1)) 2318 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1); 2319 Known = KnownBits::smax(Known0, Known1); 2320 break; 2321 case ISD::UMIN: 2322 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2323 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1); 2324 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2325 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1); 2326 Known = KnownBits::umin(Known0, Known1); 2327 break; 2328 case ISD::UMAX: 2329 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2330 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1); 2331 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2332 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1); 2333 Known = KnownBits::umax(Known0, Known1); 2334 break; 2335 } 2336 break; 2337 } 2338 case ISD::BITREVERSE: { 2339 SDValue Src = Op.getOperand(0); 2340 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2341 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2342 Depth + 1)) 2343 return true; 2344 Known.One = Known2.One.reverseBits(); 2345 Known.Zero = Known2.Zero.reverseBits(); 2346 break; 2347 } 2348 case ISD::BSWAP: { 2349 SDValue Src = Op.getOperand(0); 2350 2351 // If the only bits demanded come from one byte of the bswap result, 2352 // just shift the input byte into position to eliminate the bswap. 2353 unsigned NLZ = DemandedBits.countl_zero(); 2354 unsigned NTZ = DemandedBits.countr_zero(); 2355 2356 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2357 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2358 // have 14 leading zeros, round to 8. 2359 NLZ = alignDown(NLZ, 8); 2360 NTZ = alignDown(NTZ, 8); 2361 // If we need exactly one byte, we can do this transformation. 2362 if (BitWidth - NLZ - NTZ == 8) { 2363 // Replace this with either a left or right shift to get the byte into 2364 // the right place. 2365 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2366 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2367 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2368 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl); 2369 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2370 return TLO.CombineTo(Op, NewOp); 2371 } 2372 } 2373 2374 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2375 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2376 Depth + 1)) 2377 return true; 2378 Known.One = Known2.One.byteSwap(); 2379 Known.Zero = Known2.Zero.byteSwap(); 2380 break; 2381 } 2382 case ISD::CTPOP: { 2383 // If only 1 bit is demanded, replace with PARITY as long as we're before 2384 // op legalization. 2385 // FIXME: Limit to scalars for now. 2386 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2387 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2388 Op.getOperand(0))); 2389 2390 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2391 break; 2392 } 2393 case ISD::SIGN_EXTEND_INREG: { 2394 SDValue Op0 = Op.getOperand(0); 2395 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2396 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2397 2398 // If we only care about the highest bit, don't bother shifting right. 2399 if (DemandedBits.isSignMask()) { 2400 unsigned MinSignedBits = 2401 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2402 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2403 // However if the input is already sign extended we expect the sign 2404 // extension to be dropped altogether later and do not simplify. 2405 if (!AlreadySignExtended) { 2406 // Compute the correct shift amount type, which must be getShiftAmountTy 2407 // for scalar types after legalization. 2408 SDValue ShiftAmt = 2409 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl); 2410 return TLO.CombineTo(Op, 2411 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2412 } 2413 } 2414 2415 // If none of the extended bits are demanded, eliminate the sextinreg. 2416 if (DemandedBits.getActiveBits() <= ExVTBits) 2417 return TLO.CombineTo(Op, Op0); 2418 2419 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2420 2421 // Since the sign extended bits are demanded, we know that the sign 2422 // bit is demanded. 2423 InputDemandedBits.setBit(ExVTBits - 1); 2424 2425 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2426 Depth + 1)) 2427 return true; 2428 2429 // If the sign bit of the input is known set or clear, then we know the 2430 // top bits of the result. 2431 2432 // If the input sign bit is known zero, convert this into a zero extension. 2433 if (Known.Zero[ExVTBits - 1]) 2434 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2435 2436 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2437 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2438 Known.One.setBitsFrom(ExVTBits); 2439 Known.Zero &= Mask; 2440 } else { // Input sign bit unknown 2441 Known.Zero &= Mask; 2442 Known.One &= Mask; 2443 } 2444 break; 2445 } 2446 case ISD::BUILD_PAIR: { 2447 EVT HalfVT = Op.getOperand(0).getValueType(); 2448 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2449 2450 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2451 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2452 2453 KnownBits KnownLo, KnownHi; 2454 2455 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2456 return true; 2457 2458 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2459 return true; 2460 2461 Known = KnownHi.concat(KnownLo); 2462 break; 2463 } 2464 case ISD::ZERO_EXTEND_VECTOR_INREG: 2465 if (VT.isScalableVector()) 2466 return false; 2467 [[fallthrough]]; 2468 case ISD::ZERO_EXTEND: { 2469 SDValue Src = Op.getOperand(0); 2470 EVT SrcVT = Src.getValueType(); 2471 unsigned InBits = SrcVT.getScalarSizeInBits(); 2472 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2473 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2474 2475 // If none of the top bits are demanded, convert this into an any_extend. 2476 if (DemandedBits.getActiveBits() <= InBits) { 2477 // If we only need the non-extended bits of the bottom element 2478 // then we can just bitcast to the result. 2479 if (IsLE && IsVecInReg && DemandedElts == 1 && 2480 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2481 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2482 2483 unsigned Opc = 2484 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2485 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2486 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2487 } 2488 2489 APInt InDemandedBits = DemandedBits.trunc(InBits); 2490 APInt InDemandedElts = DemandedElts.zext(InElts); 2491 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2492 Depth + 1)) { 2493 Op->dropFlags(SDNodeFlags::NonNeg); 2494 return true; 2495 } 2496 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2497 Known = Known.zext(BitWidth); 2498 2499 // Attempt to avoid multi-use ops if we don't need anything from them. 2500 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2501 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2502 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2503 break; 2504 } 2505 case ISD::SIGN_EXTEND_VECTOR_INREG: 2506 if (VT.isScalableVector()) 2507 return false; 2508 [[fallthrough]]; 2509 case ISD::SIGN_EXTEND: { 2510 SDValue Src = Op.getOperand(0); 2511 EVT SrcVT = Src.getValueType(); 2512 unsigned InBits = SrcVT.getScalarSizeInBits(); 2513 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2514 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2515 2516 APInt InDemandedElts = DemandedElts.zext(InElts); 2517 APInt InDemandedBits = DemandedBits.trunc(InBits); 2518 2519 // Since some of the sign extended bits are demanded, we know that the sign 2520 // bit is demanded. 2521 InDemandedBits.setBit(InBits - 1); 2522 2523 // If none of the top bits are demanded, convert this into an any_extend. 2524 if (DemandedBits.getActiveBits() <= InBits) { 2525 // If we only need the non-extended bits of the bottom element 2526 // then we can just bitcast to the result. 2527 if (IsLE && IsVecInReg && DemandedElts == 1 && 2528 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2529 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2530 2531 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans. 2532 if (getBooleanContents(VT) != ZeroOrNegativeOneBooleanContent || 2533 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) != 2534 InBits) { 2535 unsigned Opc = 2536 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2537 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2538 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2539 } 2540 } 2541 2542 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2543 Depth + 1)) 2544 return true; 2545 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2546 2547 // If the sign bit is known one, the top bits match. 2548 Known = Known.sext(BitWidth); 2549 2550 // If the sign bit is known zero, convert this to a zero extend. 2551 if (Known.isNonNegative()) { 2552 unsigned Opc = 2553 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2554 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) { 2555 SDNodeFlags Flags; 2556 if (!IsVecInReg) 2557 Flags |= SDNodeFlags::NonNeg; 2558 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags)); 2559 } 2560 } 2561 2562 // Attempt to avoid multi-use ops if we don't need anything from them. 2563 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2564 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2565 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2566 break; 2567 } 2568 case ISD::ANY_EXTEND_VECTOR_INREG: 2569 if (VT.isScalableVector()) 2570 return false; 2571 [[fallthrough]]; 2572 case ISD::ANY_EXTEND: { 2573 SDValue Src = Op.getOperand(0); 2574 EVT SrcVT = Src.getValueType(); 2575 unsigned InBits = SrcVT.getScalarSizeInBits(); 2576 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2577 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2578 2579 // If we only need the bottom element then we can just bitcast. 2580 // TODO: Handle ANY_EXTEND? 2581 if (IsLE && IsVecInReg && DemandedElts == 1 && 2582 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2583 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2584 2585 APInt InDemandedBits = DemandedBits.trunc(InBits); 2586 APInt InDemandedElts = DemandedElts.zext(InElts); 2587 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2588 Depth + 1)) 2589 return true; 2590 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2591 Known = Known.anyext(BitWidth); 2592 2593 // Attempt to avoid multi-use ops if we don't need anything from them. 2594 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2595 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2596 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2597 break; 2598 } 2599 case ISD::TRUNCATE: { 2600 SDValue Src = Op.getOperand(0); 2601 2602 // Simplify the input, using demanded bit information, and compute the known 2603 // zero/one bits live out. 2604 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2605 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2606 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2607 Depth + 1)) 2608 return true; 2609 Known = Known.trunc(BitWidth); 2610 2611 // Attempt to avoid multi-use ops if we don't need anything from them. 2612 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2613 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2614 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2615 2616 // If the input is only used by this truncate, see if we can shrink it based 2617 // on the known demanded bits. 2618 switch (Src.getOpcode()) { 2619 default: 2620 break; 2621 case ISD::SRL: 2622 // Shrink SRL by a constant if none of the high bits shifted in are 2623 // demanded. 2624 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2625 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2626 // undesirable. 2627 break; 2628 2629 if (Src.getNode()->hasOneUse()) { 2630 if (isTruncateFree(Src, VT) && 2631 !isTruncateFree(Src.getValueType(), VT)) { 2632 // If truncate is only free at trunc(srl), do not turn it into 2633 // srl(trunc). The check is done by first check the truncate is free 2634 // at Src's opcode(srl), then check the truncate is not done by 2635 // referencing sub-register. In test, if both trunc(srl) and 2636 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only 2637 // trunc(srl)'s trunc is free, trunc(srl) is better. 2638 break; 2639 } 2640 2641 std::optional<uint64_t> ShAmtC = 2642 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2); 2643 if (!ShAmtC || *ShAmtC >= BitWidth) 2644 break; 2645 uint64_t ShVal = *ShAmtC; 2646 2647 APInt HighBits = 2648 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2649 HighBits.lshrInPlace(ShVal); 2650 HighBits = HighBits.trunc(BitWidth); 2651 if (!(HighBits & DemandedBits)) { 2652 // None of the shifted in bits are needed. Add a truncate of the 2653 // shift input, then shift it. 2654 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl); 2655 SDValue NewTrunc = 2656 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2657 return TLO.CombineTo( 2658 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2659 } 2660 } 2661 break; 2662 } 2663 2664 break; 2665 } 2666 case ISD::AssertZext: { 2667 // AssertZext demands all of the high bits, plus any of the low bits 2668 // demanded by its users. 2669 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2670 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2671 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2672 TLO, Depth + 1)) 2673 return true; 2674 2675 Known.Zero |= ~InMask; 2676 Known.One &= (~Known.Zero); 2677 break; 2678 } 2679 case ISD::EXTRACT_VECTOR_ELT: { 2680 SDValue Src = Op.getOperand(0); 2681 SDValue Idx = Op.getOperand(1); 2682 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2683 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2684 2685 if (SrcEltCnt.isScalable()) 2686 return false; 2687 2688 // Demand the bits from every vector element without a constant index. 2689 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2690 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2691 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2692 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2693 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2694 2695 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2696 // anything about the extended bits. 2697 APInt DemandedSrcBits = DemandedBits; 2698 if (BitWidth > EltBitWidth) 2699 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2700 2701 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2702 Depth + 1)) 2703 return true; 2704 2705 // Attempt to avoid multi-use ops if we don't need anything from them. 2706 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2707 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2708 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2709 SDValue NewOp = 2710 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2711 return TLO.CombineTo(Op, NewOp); 2712 } 2713 } 2714 2715 Known = Known2; 2716 if (BitWidth > EltBitWidth) 2717 Known = Known.anyext(BitWidth); 2718 break; 2719 } 2720 case ISD::BITCAST: { 2721 if (VT.isScalableVector()) 2722 return false; 2723 SDValue Src = Op.getOperand(0); 2724 EVT SrcVT = Src.getValueType(); 2725 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2726 2727 // If this is an FP->Int bitcast and if the sign bit is the only 2728 // thing demanded, turn this into a FGETSIGN. 2729 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2730 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2731 SrcVT.isFloatingPoint()) { 2732 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2733 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2734 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2735 SrcVT != MVT::f128) { 2736 // Cannot eliminate/lower SHL for f128 yet. 2737 EVT Ty = OpVTLegal ? VT : MVT::i32; 2738 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2739 // place. We expect the SHL to be eliminated by other optimizations. 2740 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2741 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2742 if (!OpVTLegal && OpVTSizeInBits > 32) 2743 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2744 unsigned ShVal = Op.getValueSizeInBits() - 1; 2745 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2746 return TLO.CombineTo(Op, 2747 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2748 } 2749 } 2750 2751 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2752 // Demand the elt/bit if any of the original elts/bits are demanded. 2753 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2754 unsigned Scale = BitWidth / NumSrcEltBits; 2755 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2756 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2757 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2758 for (unsigned i = 0; i != Scale; ++i) { 2759 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2760 unsigned BitOffset = EltOffset * NumSrcEltBits; 2761 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2762 if (!Sub.isZero()) { 2763 DemandedSrcBits |= Sub; 2764 for (unsigned j = 0; j != NumElts; ++j) 2765 if (DemandedElts[j]) 2766 DemandedSrcElts.setBit((j * Scale) + i); 2767 } 2768 } 2769 2770 APInt KnownSrcUndef, KnownSrcZero; 2771 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2772 KnownSrcZero, TLO, Depth + 1)) 2773 return true; 2774 2775 KnownBits KnownSrcBits; 2776 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2777 KnownSrcBits, TLO, Depth + 1)) 2778 return true; 2779 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2780 // TODO - bigendian once we have test coverage. 2781 unsigned Scale = NumSrcEltBits / BitWidth; 2782 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2783 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2784 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2785 for (unsigned i = 0; i != NumElts; ++i) 2786 if (DemandedElts[i]) { 2787 unsigned Offset = (i % Scale) * BitWidth; 2788 DemandedSrcBits.insertBits(DemandedBits, Offset); 2789 DemandedSrcElts.setBit(i / Scale); 2790 } 2791 2792 if (SrcVT.isVector()) { 2793 APInt KnownSrcUndef, KnownSrcZero; 2794 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2795 KnownSrcZero, TLO, Depth + 1)) 2796 return true; 2797 } 2798 2799 KnownBits KnownSrcBits; 2800 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2801 KnownSrcBits, TLO, Depth + 1)) 2802 return true; 2803 2804 // Attempt to avoid multi-use ops if we don't need anything from them. 2805 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2806 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2807 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2808 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc); 2809 return TLO.CombineTo(Op, NewOp); 2810 } 2811 } 2812 } 2813 2814 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2815 // recursive call where Known may be useful to the caller. 2816 if (Depth > 0) { 2817 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2818 return false; 2819 } 2820 break; 2821 } 2822 case ISD::MUL: 2823 if (DemandedBits.isPowerOf2()) { 2824 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2825 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2826 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2827 unsigned CTZ = DemandedBits.countr_zero(); 2828 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2829 if (C && C->getAPIntValue().countr_zero() == CTZ) { 2830 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl); 2831 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2832 return TLO.CombineTo(Op, Shl); 2833 } 2834 } 2835 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2836 // X * X is odd iff X is odd. 2837 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2838 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2839 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2840 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2841 return TLO.CombineTo(Op, And1); 2842 } 2843 [[fallthrough]]; 2844 case ISD::ADD: 2845 case ISD::SUB: { 2846 // Add, Sub, and Mul don't demand any bits in positions beyond that 2847 // of the highest bit demanded of them. 2848 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2849 SDNodeFlags Flags = Op.getNode()->getFlags(); 2850 unsigned DemandedBitsLZ = DemandedBits.countl_zero(); 2851 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2852 KnownBits KnownOp0, KnownOp1; 2853 auto GetDemandedBitsLHSMask = [&](APInt Demanded, 2854 const KnownBits &KnownRHS) { 2855 if (Op.getOpcode() == ISD::MUL) 2856 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros()); 2857 return Demanded; 2858 }; 2859 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO, 2860 Depth + 1) || 2861 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1), 2862 DemandedElts, KnownOp0, TLO, Depth + 1) || 2863 // See if the operation should be performed at a smaller bit width. 2864 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2865 // Disable the nsw and nuw flags. We can no longer guarantee that we 2866 // won't wrap after simplification. 2867 Op->dropFlags(SDNodeFlags::NoWrap); 2868 return true; 2869 } 2870 2871 // neg x with only low bit demanded is simply x. 2872 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() && 2873 isNullConstant(Op0)) 2874 return TLO.CombineTo(Op, Op1); 2875 2876 // Attempt to avoid multi-use ops if we don't need anything from them. 2877 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2878 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2879 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2880 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2881 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2882 if (DemandedOp0 || DemandedOp1) { 2883 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2884 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2885 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, 2886 Flags & ~SDNodeFlags::NoWrap); 2887 return TLO.CombineTo(Op, NewOp); 2888 } 2889 } 2890 2891 // If we have a constant operand, we may be able to turn it into -1 if we 2892 // do not demand the high bits. This can make the constant smaller to 2893 // encode, allow more general folding, or match specialized instruction 2894 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2895 // is probably not useful (and could be detrimental). 2896 ConstantSDNode *C = isConstOrConstSplat(Op1); 2897 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2898 if (C && !C->isAllOnes() && !C->isOne() && 2899 (C->getAPIntValue() | HighMask).isAllOnes()) { 2900 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2901 // Disable the nsw and nuw flags. We can no longer guarantee that we 2902 // won't wrap after simplification. 2903 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, 2904 Flags & ~SDNodeFlags::NoWrap); 2905 return TLO.CombineTo(Op, NewOp); 2906 } 2907 2908 // Match a multiply with a disguised negated-power-of-2 and convert to a 2909 // an equivalent shift-left amount. 2910 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2911 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2912 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2913 return 0; 2914 2915 // Don't touch opaque constants. Also, ignore zero and power-of-2 2916 // multiplies. Those will get folded later. 2917 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2918 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2919 !MulC->getAPIntValue().isPowerOf2()) { 2920 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2921 if (UnmaskedC.isNegatedPowerOf2()) 2922 return (-UnmaskedC).logBase2(); 2923 } 2924 return 0; 2925 }; 2926 2927 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, 2928 unsigned ShlAmt) { 2929 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl); 2930 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2931 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2932 return TLO.CombineTo(Op, Res); 2933 }; 2934 2935 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2936 if (Op.getOpcode() == ISD::ADD) { 2937 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2938 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2939 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2940 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2941 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2942 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2943 } 2944 if (Op.getOpcode() == ISD::SUB) { 2945 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2946 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2947 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2948 } 2949 } 2950 2951 if (Op.getOpcode() == ISD::MUL) { 2952 Known = KnownBits::mul(KnownOp0, KnownOp1); 2953 } else { // Op.getOpcode() is either ISD::ADD or ISD::SUB. 2954 Known = KnownBits::computeForAddSub( 2955 Op.getOpcode() == ISD::ADD, Flags.hasNoSignedWrap(), 2956 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1); 2957 } 2958 break; 2959 } 2960 default: 2961 // We also ask the target about intrinsics (which could be specific to it). 2962 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2963 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 2964 // TODO: Probably okay to remove after audit; here to reduce change size 2965 // in initial enablement patch for scalable vectors 2966 if (Op.getValueType().isScalableVector()) 2967 break; 2968 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2969 Known, TLO, Depth)) 2970 return true; 2971 break; 2972 } 2973 2974 // Just use computeKnownBits to compute output bits. 2975 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2976 break; 2977 } 2978 2979 // If we know the value of all of the demanded bits, return this as a 2980 // constant. 2981 if (!isTargetCanonicalConstantNode(Op) && 2982 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2983 // Avoid folding to a constant if any OpaqueConstant is involved. 2984 const SDNode *N = Op.getNode(); 2985 for (SDNode *Op : 2986 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2987 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 2988 if (C->isOpaque()) 2989 return false; 2990 } 2991 if (VT.isInteger()) 2992 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2993 if (VT.isFloatingPoint()) 2994 return TLO.CombineTo( 2995 Op, TLO.DAG.getConstantFP(APFloat(VT.getFltSemantics(), Known.One), 2996 dl, VT)); 2997 } 2998 2999 // A multi use 'all demanded elts' simplify failed to find any knownbits. 3000 // Try again just for the original demanded elts. 3001 // Ensure we do this AFTER constant folding above. 3002 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes()) 3003 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth); 3004 3005 return false; 3006 } 3007 3008 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 3009 const APInt &DemandedElts, 3010 DAGCombinerInfo &DCI) const { 3011 SelectionDAG &DAG = DCI.DAG; 3012 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 3013 !DCI.isBeforeLegalizeOps()); 3014 3015 APInt KnownUndef, KnownZero; 3016 bool Simplified = 3017 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 3018 if (Simplified) { 3019 DCI.AddToWorklist(Op.getNode()); 3020 DCI.CommitTargetLoweringOpt(TLO); 3021 } 3022 3023 return Simplified; 3024 } 3025 3026 /// Given a vector binary operation and known undefined elements for each input 3027 /// operand, compute whether each element of the output is undefined. 3028 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 3029 const APInt &UndefOp0, 3030 const APInt &UndefOp1) { 3031 EVT VT = BO.getValueType(); 3032 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 3033 "Vector binop only"); 3034 3035 EVT EltVT = VT.getVectorElementType(); 3036 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1; 3037 assert(UndefOp0.getBitWidth() == NumElts && 3038 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 3039 3040 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 3041 const APInt &UndefVals) { 3042 if (UndefVals[Index]) 3043 return DAG.getUNDEF(EltVT); 3044 3045 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 3046 // Try hard to make sure that the getNode() call is not creating temporary 3047 // nodes. Ignore opaque integers because they do not constant fold. 3048 SDValue Elt = BV->getOperand(Index); 3049 auto *C = dyn_cast<ConstantSDNode>(Elt); 3050 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 3051 return Elt; 3052 } 3053 3054 return SDValue(); 3055 }; 3056 3057 APInt KnownUndef = APInt::getZero(NumElts); 3058 for (unsigned i = 0; i != NumElts; ++i) { 3059 // If both inputs for this element are either constant or undef and match 3060 // the element type, compute the constant/undef result for this element of 3061 // the vector. 3062 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 3063 // not handle FP constants. The code within getNode() should be refactored 3064 // to avoid the danger of creating a bogus temporary node here. 3065 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 3066 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 3067 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 3068 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 3069 KnownUndef.setBit(i); 3070 } 3071 return KnownUndef; 3072 } 3073 3074 bool TargetLowering::SimplifyDemandedVectorElts( 3075 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 3076 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 3077 bool AssumeSingleUse) const { 3078 EVT VT = Op.getValueType(); 3079 unsigned Opcode = Op.getOpcode(); 3080 APInt DemandedElts = OriginalDemandedElts; 3081 unsigned NumElts = DemandedElts.getBitWidth(); 3082 assert(VT.isVector() && "Expected vector op"); 3083 3084 KnownUndef = KnownZero = APInt::getZero(NumElts); 3085 3086 if (!shouldSimplifyDemandedVectorElts(Op, TLO)) 3087 return false; 3088 3089 // TODO: For now we assume we know nothing about scalable vectors. 3090 if (VT.isScalableVector()) 3091 return false; 3092 3093 assert(VT.getVectorNumElements() == NumElts && 3094 "Mask size mismatches value type element count!"); 3095 3096 // Undef operand. 3097 if (Op.isUndef()) { 3098 KnownUndef.setAllBits(); 3099 return false; 3100 } 3101 3102 // If Op has other users, assume that all elements are needed. 3103 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) 3104 DemandedElts.setAllBits(); 3105 3106 // Not demanding any elements from Op. 3107 if (DemandedElts == 0) { 3108 KnownUndef.setAllBits(); 3109 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3110 } 3111 3112 // Limit search depth. 3113 if (Depth >= SelectionDAG::MaxRecursionDepth) 3114 return false; 3115 3116 SDLoc DL(Op); 3117 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 3118 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 3119 3120 // Helper for demanding the specified elements and all the bits of both binary 3121 // operands. 3122 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 3123 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 3124 TLO.DAG, Depth + 1); 3125 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 3126 TLO.DAG, Depth + 1); 3127 if (NewOp0 || NewOp1) { 3128 SDValue NewOp = 3129 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, 3130 NewOp1 ? NewOp1 : Op1, Op->getFlags()); 3131 return TLO.CombineTo(Op, NewOp); 3132 } 3133 return false; 3134 }; 3135 3136 switch (Opcode) { 3137 case ISD::SCALAR_TO_VECTOR: { 3138 if (!DemandedElts[0]) { 3139 KnownUndef.setAllBits(); 3140 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3141 } 3142 SDValue ScalarSrc = Op.getOperand(0); 3143 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 3144 SDValue Src = ScalarSrc.getOperand(0); 3145 SDValue Idx = ScalarSrc.getOperand(1); 3146 EVT SrcVT = Src.getValueType(); 3147 3148 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 3149 3150 if (SrcEltCnt.isScalable()) 3151 return false; 3152 3153 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 3154 if (isNullConstant(Idx)) { 3155 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 3156 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 3157 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 3158 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3159 TLO, Depth + 1)) 3160 return true; 3161 } 3162 } 3163 KnownUndef.setHighBits(NumElts - 1); 3164 break; 3165 } 3166 case ISD::BITCAST: { 3167 SDValue Src = Op.getOperand(0); 3168 EVT SrcVT = Src.getValueType(); 3169 3170 // We only handle vectors here. 3171 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 3172 if (!SrcVT.isVector()) 3173 break; 3174 3175 // Fast handling of 'identity' bitcasts. 3176 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 3177 if (NumSrcElts == NumElts) 3178 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 3179 KnownZero, TLO, Depth + 1); 3180 3181 APInt SrcDemandedElts, SrcZero, SrcUndef; 3182 3183 // Bitcast from 'large element' src vector to 'small element' vector, we 3184 // must demand a source element if any DemandedElt maps to it. 3185 if ((NumElts % NumSrcElts) == 0) { 3186 unsigned Scale = NumElts / NumSrcElts; 3187 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3188 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3189 TLO, Depth + 1)) 3190 return true; 3191 3192 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 3193 // of the large element. 3194 // TODO - bigendian once we have test coverage. 3195 if (IsLE) { 3196 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 3197 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 3198 for (unsigned i = 0; i != NumElts; ++i) 3199 if (DemandedElts[i]) { 3200 unsigned Ofs = (i % Scale) * EltSizeInBits; 3201 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 3202 } 3203 3204 KnownBits Known; 3205 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 3206 TLO, Depth + 1)) 3207 return true; 3208 3209 // The bitcast has split each wide element into a number of 3210 // narrow subelements. We have just computed the Known bits 3211 // for wide elements. See if element splitting results in 3212 // some subelements being zero. Only for demanded elements! 3213 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 3214 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 3215 .isAllOnes()) 3216 continue; 3217 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 3218 unsigned Elt = Scale * SrcElt + SubElt; 3219 if (DemandedElts[Elt]) 3220 KnownZero.setBit(Elt); 3221 } 3222 } 3223 } 3224 3225 // If the src element is zero/undef then all the output elements will be - 3226 // only demanded elements are guaranteed to be correct. 3227 for (unsigned i = 0; i != NumSrcElts; ++i) { 3228 if (SrcDemandedElts[i]) { 3229 if (SrcZero[i]) 3230 KnownZero.setBits(i * Scale, (i + 1) * Scale); 3231 if (SrcUndef[i]) 3232 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 3233 } 3234 } 3235 } 3236 3237 // Bitcast from 'small element' src vector to 'large element' vector, we 3238 // demand all smaller source elements covered by the larger demanded element 3239 // of this vector. 3240 if ((NumSrcElts % NumElts) == 0) { 3241 unsigned Scale = NumSrcElts / NumElts; 3242 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3243 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3244 TLO, Depth + 1)) 3245 return true; 3246 3247 // If all the src elements covering an output element are zero/undef, then 3248 // the output element will be as well, assuming it was demanded. 3249 for (unsigned i = 0; i != NumElts; ++i) { 3250 if (DemandedElts[i]) { 3251 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 3252 KnownZero.setBit(i); 3253 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 3254 KnownUndef.setBit(i); 3255 } 3256 } 3257 } 3258 break; 3259 } 3260 case ISD::FREEZE: { 3261 SDValue N0 = Op.getOperand(0); 3262 if (TLO.DAG.isGuaranteedNotToBeUndefOrPoison(N0, DemandedElts, 3263 /*PoisonOnly=*/false)) 3264 return TLO.CombineTo(Op, N0); 3265 3266 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE 3267 // freeze(op(x, ...)) -> op(freeze(x), ...). 3268 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) 3269 return TLO.CombineTo( 3270 Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, 3271 TLO.DAG.getFreeze(N0.getOperand(0)))); 3272 break; 3273 } 3274 case ISD::BUILD_VECTOR: { 3275 // Check all elements and simplify any unused elements with UNDEF. 3276 if (!DemandedElts.isAllOnes()) { 3277 // Don't simplify BROADCASTS. 3278 if (llvm::any_of(Op->op_values(), 3279 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 3280 SmallVector<SDValue, 32> Ops(Op->ops()); 3281 bool Updated = false; 3282 for (unsigned i = 0; i != NumElts; ++i) { 3283 if (!DemandedElts[i] && !Ops[i].isUndef()) { 3284 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 3285 KnownUndef.setBit(i); 3286 Updated = true; 3287 } 3288 } 3289 if (Updated) 3290 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 3291 } 3292 } 3293 for (unsigned i = 0; i != NumElts; ++i) { 3294 SDValue SrcOp = Op.getOperand(i); 3295 if (SrcOp.isUndef()) { 3296 KnownUndef.setBit(i); 3297 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 3298 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 3299 KnownZero.setBit(i); 3300 } 3301 } 3302 break; 3303 } 3304 case ISD::CONCAT_VECTORS: { 3305 EVT SubVT = Op.getOperand(0).getValueType(); 3306 unsigned NumSubVecs = Op.getNumOperands(); 3307 unsigned NumSubElts = SubVT.getVectorNumElements(); 3308 for (unsigned i = 0; i != NumSubVecs; ++i) { 3309 SDValue SubOp = Op.getOperand(i); 3310 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3311 APInt SubUndef, SubZero; 3312 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 3313 Depth + 1)) 3314 return true; 3315 KnownUndef.insertBits(SubUndef, i * NumSubElts); 3316 KnownZero.insertBits(SubZero, i * NumSubElts); 3317 } 3318 3319 // Attempt to avoid multi-use ops if we don't need anything from them. 3320 if (!DemandedElts.isAllOnes()) { 3321 bool FoundNewSub = false; 3322 SmallVector<SDValue, 2> DemandedSubOps; 3323 for (unsigned i = 0; i != NumSubVecs; ++i) { 3324 SDValue SubOp = Op.getOperand(i); 3325 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3326 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 3327 SubOp, SubElts, TLO.DAG, Depth + 1); 3328 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 3329 FoundNewSub = NewSubOp ? true : FoundNewSub; 3330 } 3331 if (FoundNewSub) { 3332 SDValue NewOp = 3333 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 3334 return TLO.CombineTo(Op, NewOp); 3335 } 3336 } 3337 break; 3338 } 3339 case ISD::INSERT_SUBVECTOR: { 3340 // Demand any elements from the subvector and the remainder from the src its 3341 // inserted into. 3342 SDValue Src = Op.getOperand(0); 3343 SDValue Sub = Op.getOperand(1); 3344 uint64_t Idx = Op.getConstantOperandVal(2); 3345 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3346 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3347 APInt DemandedSrcElts = DemandedElts; 3348 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3349 3350 APInt SubUndef, SubZero; 3351 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 3352 Depth + 1)) 3353 return true; 3354 3355 // If none of the src operand elements are demanded, replace it with undef. 3356 if (!DemandedSrcElts && !Src.isUndef()) 3357 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 3358 TLO.DAG.getUNDEF(VT), Sub, 3359 Op.getOperand(2))); 3360 3361 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 3362 TLO, Depth + 1)) 3363 return true; 3364 KnownUndef.insertBits(SubUndef, Idx); 3365 KnownZero.insertBits(SubZero, Idx); 3366 3367 // Attempt to avoid multi-use ops if we don't need anything from them. 3368 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3369 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3370 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3371 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3372 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3373 if (NewSrc || NewSub) { 3374 NewSrc = NewSrc ? NewSrc : Src; 3375 NewSub = NewSub ? NewSub : Sub; 3376 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3377 NewSub, Op.getOperand(2)); 3378 return TLO.CombineTo(Op, NewOp); 3379 } 3380 } 3381 break; 3382 } 3383 case ISD::EXTRACT_SUBVECTOR: { 3384 // Offset the demanded elts by the subvector index. 3385 SDValue Src = Op.getOperand(0); 3386 if (Src.getValueType().isScalableVector()) 3387 break; 3388 uint64_t Idx = Op.getConstantOperandVal(1); 3389 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3390 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3391 3392 APInt SrcUndef, SrcZero; 3393 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3394 Depth + 1)) 3395 return true; 3396 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3397 KnownZero = SrcZero.extractBits(NumElts, Idx); 3398 3399 // Attempt to avoid multi-use ops if we don't need anything from them. 3400 if (!DemandedElts.isAllOnes()) { 3401 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3402 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3403 if (NewSrc) { 3404 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3405 Op.getOperand(1)); 3406 return TLO.CombineTo(Op, NewOp); 3407 } 3408 } 3409 break; 3410 } 3411 case ISD::INSERT_VECTOR_ELT: { 3412 SDValue Vec = Op.getOperand(0); 3413 SDValue Scl = Op.getOperand(1); 3414 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3415 3416 // For a legal, constant insertion index, if we don't need this insertion 3417 // then strip it, else remove it from the demanded elts. 3418 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3419 unsigned Idx = CIdx->getZExtValue(); 3420 if (!DemandedElts[Idx]) 3421 return TLO.CombineTo(Op, Vec); 3422 3423 APInt DemandedVecElts(DemandedElts); 3424 DemandedVecElts.clearBit(Idx); 3425 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3426 KnownZero, TLO, Depth + 1)) 3427 return true; 3428 3429 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3430 3431 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3432 break; 3433 } 3434 3435 APInt VecUndef, VecZero; 3436 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3437 Depth + 1)) 3438 return true; 3439 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3440 break; 3441 } 3442 case ISD::VSELECT: { 3443 SDValue Sel = Op.getOperand(0); 3444 SDValue LHS = Op.getOperand(1); 3445 SDValue RHS = Op.getOperand(2); 3446 3447 // Try to transform the select condition based on the current demanded 3448 // elements. 3449 APInt UndefSel, ZeroSel; 3450 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO, 3451 Depth + 1)) 3452 return true; 3453 3454 // See if we can simplify either vselect operand. 3455 APInt DemandedLHS(DemandedElts); 3456 APInt DemandedRHS(DemandedElts); 3457 APInt UndefLHS, ZeroLHS; 3458 APInt UndefRHS, ZeroRHS; 3459 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3460 Depth + 1)) 3461 return true; 3462 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3463 Depth + 1)) 3464 return true; 3465 3466 KnownUndef = UndefLHS & UndefRHS; 3467 KnownZero = ZeroLHS & ZeroRHS; 3468 3469 // If we know that the selected element is always zero, we don't need the 3470 // select value element. 3471 APInt DemandedSel = DemandedElts & ~KnownZero; 3472 if (DemandedSel != DemandedElts) 3473 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO, 3474 Depth + 1)) 3475 return true; 3476 3477 break; 3478 } 3479 case ISD::VECTOR_SHUFFLE: { 3480 SDValue LHS = Op.getOperand(0); 3481 SDValue RHS = Op.getOperand(1); 3482 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3483 3484 // Collect demanded elements from shuffle operands.. 3485 APInt DemandedLHS(NumElts, 0); 3486 APInt DemandedRHS(NumElts, 0); 3487 for (unsigned i = 0; i != NumElts; ++i) { 3488 int M = ShuffleMask[i]; 3489 if (M < 0 || !DemandedElts[i]) 3490 continue; 3491 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3492 if (M < (int)NumElts) 3493 DemandedLHS.setBit(M); 3494 else 3495 DemandedRHS.setBit(M - NumElts); 3496 } 3497 3498 // See if we can simplify either shuffle operand. 3499 APInt UndefLHS, ZeroLHS; 3500 APInt UndefRHS, ZeroRHS; 3501 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3502 Depth + 1)) 3503 return true; 3504 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3505 Depth + 1)) 3506 return true; 3507 3508 // Simplify mask using undef elements from LHS/RHS. 3509 bool Updated = false; 3510 bool IdentityLHS = true, IdentityRHS = true; 3511 SmallVector<int, 32> NewMask(ShuffleMask); 3512 for (unsigned i = 0; i != NumElts; ++i) { 3513 int &M = NewMask[i]; 3514 if (M < 0) 3515 continue; 3516 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3517 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3518 Updated = true; 3519 M = -1; 3520 } 3521 IdentityLHS &= (M < 0) || (M == (int)i); 3522 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3523 } 3524 3525 // Update legal shuffle masks based on demanded elements if it won't reduce 3526 // to Identity which can cause premature removal of the shuffle mask. 3527 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3528 SDValue LegalShuffle = 3529 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG); 3530 if (LegalShuffle) 3531 return TLO.CombineTo(Op, LegalShuffle); 3532 } 3533 3534 // Propagate undef/zero elements from LHS/RHS. 3535 for (unsigned i = 0; i != NumElts; ++i) { 3536 int M = ShuffleMask[i]; 3537 if (M < 0) { 3538 KnownUndef.setBit(i); 3539 } else if (M < (int)NumElts) { 3540 if (UndefLHS[M]) 3541 KnownUndef.setBit(i); 3542 if (ZeroLHS[M]) 3543 KnownZero.setBit(i); 3544 } else { 3545 if (UndefRHS[M - NumElts]) 3546 KnownUndef.setBit(i); 3547 if (ZeroRHS[M - NumElts]) 3548 KnownZero.setBit(i); 3549 } 3550 } 3551 break; 3552 } 3553 case ISD::ANY_EXTEND_VECTOR_INREG: 3554 case ISD::SIGN_EXTEND_VECTOR_INREG: 3555 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3556 APInt SrcUndef, SrcZero; 3557 SDValue Src = Op.getOperand(0); 3558 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3559 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3560 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3561 Depth + 1)) 3562 return true; 3563 KnownZero = SrcZero.zextOrTrunc(NumElts); 3564 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3565 3566 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3567 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3568 DemandedSrcElts == 1) { 3569 // aext - if we just need the bottom element then we can bitcast. 3570 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3571 } 3572 3573 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3574 // zext(undef) upper bits are guaranteed to be zero. 3575 if (DemandedElts.isSubsetOf(KnownUndef)) 3576 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3577 KnownUndef.clearAllBits(); 3578 3579 // zext - if we just need the bottom element then we can mask: 3580 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3581 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3582 Op->isOnlyUserOf(Src.getNode()) && 3583 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3584 SDLoc DL(Op); 3585 EVT SrcVT = Src.getValueType(); 3586 EVT SrcSVT = SrcVT.getScalarType(); 3587 SmallVector<SDValue> MaskElts; 3588 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3589 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3590 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3591 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3592 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3593 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3594 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3595 } 3596 } 3597 } 3598 break; 3599 } 3600 3601 // TODO: There are more binop opcodes that could be handled here - MIN, 3602 // MAX, saturated math, etc. 3603 case ISD::ADD: { 3604 SDValue Op0 = Op.getOperand(0); 3605 SDValue Op1 = Op.getOperand(1); 3606 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3607 APInt UndefLHS, ZeroLHS; 3608 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3609 Depth + 1, /*AssumeSingleUse*/ true)) 3610 return true; 3611 } 3612 [[fallthrough]]; 3613 } 3614 case ISD::AVGCEILS: 3615 case ISD::AVGCEILU: 3616 case ISD::AVGFLOORS: 3617 case ISD::AVGFLOORU: 3618 case ISD::OR: 3619 case ISD::XOR: 3620 case ISD::SUB: 3621 case ISD::FADD: 3622 case ISD::FSUB: 3623 case ISD::FMUL: 3624 case ISD::FDIV: 3625 case ISD::FREM: { 3626 SDValue Op0 = Op.getOperand(0); 3627 SDValue Op1 = Op.getOperand(1); 3628 3629 APInt UndefRHS, ZeroRHS; 3630 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3631 Depth + 1)) 3632 return true; 3633 APInt UndefLHS, ZeroLHS; 3634 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3635 Depth + 1)) 3636 return true; 3637 3638 KnownZero = ZeroLHS & ZeroRHS; 3639 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3640 3641 // Attempt to avoid multi-use ops if we don't need anything from them. 3642 // TODO - use KnownUndef to relax the demandedelts? 3643 if (!DemandedElts.isAllOnes()) 3644 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3645 return true; 3646 break; 3647 } 3648 case ISD::SHL: 3649 case ISD::SRL: 3650 case ISD::SRA: 3651 case ISD::ROTL: 3652 case ISD::ROTR: { 3653 SDValue Op0 = Op.getOperand(0); 3654 SDValue Op1 = Op.getOperand(1); 3655 3656 APInt UndefRHS, ZeroRHS; 3657 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3658 Depth + 1)) 3659 return true; 3660 APInt UndefLHS, ZeroLHS; 3661 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3662 Depth + 1)) 3663 return true; 3664 3665 KnownZero = ZeroLHS; 3666 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3667 3668 // Attempt to avoid multi-use ops if we don't need anything from them. 3669 // TODO - use KnownUndef to relax the demandedelts? 3670 if (!DemandedElts.isAllOnes()) 3671 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3672 return true; 3673 break; 3674 } 3675 case ISD::MUL: 3676 case ISD::MULHU: 3677 case ISD::MULHS: 3678 case ISD::AND: { 3679 SDValue Op0 = Op.getOperand(0); 3680 SDValue Op1 = Op.getOperand(1); 3681 3682 APInt SrcUndef, SrcZero; 3683 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3684 Depth + 1)) 3685 return true; 3686 // If we know that a demanded element was zero in Op1 we don't need to 3687 // demand it in Op0 - its guaranteed to be zero. 3688 APInt DemandedElts0 = DemandedElts & ~SrcZero; 3689 if (SimplifyDemandedVectorElts(Op0, DemandedElts0, KnownUndef, KnownZero, 3690 TLO, Depth + 1)) 3691 return true; 3692 3693 KnownUndef &= DemandedElts0; 3694 KnownZero &= DemandedElts0; 3695 3696 // If every element pair has a zero/undef then just fold to zero. 3697 // fold (and x, undef) -> 0 / (and x, 0) -> 0 3698 // fold (mul x, undef) -> 0 / (mul x, 0) -> 0 3699 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef)) 3700 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3701 3702 // If either side has a zero element, then the result element is zero, even 3703 // if the other is an UNDEF. 3704 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3705 // and then handle 'and' nodes with the rest of the binop opcodes. 3706 KnownZero |= SrcZero; 3707 KnownUndef &= SrcUndef; 3708 KnownUndef &= ~KnownZero; 3709 3710 // Attempt to avoid multi-use ops if we don't need anything from them. 3711 if (!DemandedElts.isAllOnes()) 3712 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3713 return true; 3714 break; 3715 } 3716 case ISD::TRUNCATE: 3717 case ISD::SIGN_EXTEND: 3718 case ISD::ZERO_EXTEND: 3719 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3720 KnownZero, TLO, Depth + 1)) 3721 return true; 3722 3723 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3724 // zext(undef) upper bits are guaranteed to be zero. 3725 if (DemandedElts.isSubsetOf(KnownUndef)) 3726 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3727 KnownUndef.clearAllBits(); 3728 } 3729 break; 3730 default: { 3731 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3732 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3733 KnownZero, TLO, Depth)) 3734 return true; 3735 } else { 3736 KnownBits Known; 3737 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3738 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3739 TLO, Depth, AssumeSingleUse)) 3740 return true; 3741 } 3742 break; 3743 } 3744 } 3745 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3746 3747 // Constant fold all undef cases. 3748 // TODO: Handle zero cases as well. 3749 if (DemandedElts.isSubsetOf(KnownUndef)) 3750 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3751 3752 return false; 3753 } 3754 3755 /// Determine which of the bits specified in Mask are known to be either zero or 3756 /// one and return them in the Known. 3757 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3758 KnownBits &Known, 3759 const APInt &DemandedElts, 3760 const SelectionDAG &DAG, 3761 unsigned Depth) const { 3762 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3763 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3764 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3765 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3766 "Should use MaskedValueIsZero if you don't know whether Op" 3767 " is a target node!"); 3768 Known.resetAll(); 3769 } 3770 3771 void TargetLowering::computeKnownBitsForTargetInstr( 3772 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3773 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3774 unsigned Depth) const { 3775 Known.resetAll(); 3776 } 3777 3778 void TargetLowering::computeKnownBitsForFrameIndex( 3779 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3780 // The low bits are known zero if the pointer is aligned. 3781 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3782 } 3783 3784 Align TargetLowering::computeKnownAlignForTargetInstr( 3785 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3786 unsigned Depth) const { 3787 return Align(1); 3788 } 3789 3790 /// This method can be implemented by targets that want to expose additional 3791 /// information about sign bits to the DAG Combiner. 3792 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3793 const APInt &, 3794 const SelectionDAG &, 3795 unsigned Depth) const { 3796 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3797 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3798 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3799 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3800 "Should use ComputeNumSignBits if you don't know whether Op" 3801 " is a target node!"); 3802 return 1; 3803 } 3804 3805 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3806 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3807 const MachineRegisterInfo &MRI, unsigned Depth) const { 3808 return 1; 3809 } 3810 3811 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3812 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3813 TargetLoweringOpt &TLO, unsigned Depth) const { 3814 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3815 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3816 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3817 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3818 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3819 " is a target node!"); 3820 return false; 3821 } 3822 3823 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3824 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3825 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3826 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3827 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3828 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3829 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3830 "Should use SimplifyDemandedBits if you don't know whether Op" 3831 " is a target node!"); 3832 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3833 return false; 3834 } 3835 3836 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3837 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3838 SelectionDAG &DAG, unsigned Depth) const { 3839 assert( 3840 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3841 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3842 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3843 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3844 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3845 " is a target node!"); 3846 return SDValue(); 3847 } 3848 3849 SDValue 3850 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3851 SDValue N1, MutableArrayRef<int> Mask, 3852 SelectionDAG &DAG) const { 3853 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3854 if (!LegalMask) { 3855 std::swap(N0, N1); 3856 ShuffleVectorSDNode::commuteMask(Mask); 3857 LegalMask = isShuffleMaskLegal(Mask, VT); 3858 } 3859 3860 if (!LegalMask) 3861 return SDValue(); 3862 3863 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3864 } 3865 3866 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3867 return nullptr; 3868 } 3869 3870 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3871 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3872 bool PoisonOnly, unsigned Depth) const { 3873 assert( 3874 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3875 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3876 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3877 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3878 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3879 " is a target node!"); 3880 3881 // If Op can't create undef/poison and none of its operands are undef/poison 3882 // then Op is never undef/poison. 3883 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, PoisonOnly, 3884 /*ConsiderFlags*/ true, Depth) && 3885 all_of(Op->ops(), [&](SDValue V) { 3886 return DAG.isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, 3887 Depth + 1); 3888 }); 3889 } 3890 3891 bool TargetLowering::canCreateUndefOrPoisonForTargetNode( 3892 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3893 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const { 3894 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3895 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3896 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3897 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3898 "Should use canCreateUndefOrPoison if you don't know whether Op" 3899 " is a target node!"); 3900 // Be conservative and return true. 3901 return true; 3902 } 3903 3904 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3905 const SelectionDAG &DAG, 3906 bool SNaN, 3907 unsigned Depth) const { 3908 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3909 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3910 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3911 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3912 "Should use isKnownNeverNaN if you don't know whether Op" 3913 " is a target node!"); 3914 return false; 3915 } 3916 3917 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3918 const APInt &DemandedElts, 3919 APInt &UndefElts, 3920 const SelectionDAG &DAG, 3921 unsigned Depth) const { 3922 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3923 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3924 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3925 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3926 "Should use isSplatValue if you don't know whether Op" 3927 " is a target node!"); 3928 return false; 3929 } 3930 3931 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3932 // work with truncating build vectors and vectors with elements of less than 3933 // 8 bits. 3934 bool TargetLowering::isConstTrueVal(SDValue N) const { 3935 if (!N) 3936 return false; 3937 3938 unsigned EltWidth; 3939 APInt CVal; 3940 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3941 /*AllowTruncation=*/true)) { 3942 CVal = CN->getAPIntValue(); 3943 EltWidth = N.getValueType().getScalarSizeInBits(); 3944 } else 3945 return false; 3946 3947 // If this is a truncating splat, truncate the splat value. 3948 // Otherwise, we may fail to match the expected values below. 3949 if (EltWidth < CVal.getBitWidth()) 3950 CVal = CVal.trunc(EltWidth); 3951 3952 switch (getBooleanContents(N.getValueType())) { 3953 case UndefinedBooleanContent: 3954 return CVal[0]; 3955 case ZeroOrOneBooleanContent: 3956 return CVal.isOne(); 3957 case ZeroOrNegativeOneBooleanContent: 3958 return CVal.isAllOnes(); 3959 } 3960 3961 llvm_unreachable("Invalid boolean contents"); 3962 } 3963 3964 bool TargetLowering::isConstFalseVal(SDValue N) const { 3965 if (!N) 3966 return false; 3967 3968 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3969 if (!CN) { 3970 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3971 if (!BV) 3972 return false; 3973 3974 // Only interested in constant splats, we don't care about undef 3975 // elements in identifying boolean constants and getConstantSplatNode 3976 // returns NULL if all ops are undef; 3977 CN = BV->getConstantSplatNode(); 3978 if (!CN) 3979 return false; 3980 } 3981 3982 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3983 return !CN->getAPIntValue()[0]; 3984 3985 return CN->isZero(); 3986 } 3987 3988 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3989 bool SExt) const { 3990 if (VT == MVT::i1) 3991 return N->isOne(); 3992 3993 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3994 switch (Cnt) { 3995 case TargetLowering::ZeroOrOneBooleanContent: 3996 // An extended value of 1 is always true, unless its original type is i1, 3997 // in which case it will be sign extended to -1. 3998 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3999 case TargetLowering::UndefinedBooleanContent: 4000 case TargetLowering::ZeroOrNegativeOneBooleanContent: 4001 return N->isAllOnes() && SExt; 4002 } 4003 llvm_unreachable("Unexpected enumeration."); 4004 } 4005 4006 /// This helper function of SimplifySetCC tries to optimize the comparison when 4007 /// either operand of the SetCC node is a bitwise-and instruction. 4008 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 4009 ISD::CondCode Cond, const SDLoc &DL, 4010 DAGCombinerInfo &DCI) const { 4011 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 4012 std::swap(N0, N1); 4013 4014 SelectionDAG &DAG = DCI.DAG; 4015 EVT OpVT = N0.getValueType(); 4016 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 4017 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 4018 return SDValue(); 4019 4020 // (X & Y) != 0 --> zextOrTrunc(X & Y) 4021 // iff everything but LSB is known zero: 4022 if (Cond == ISD::SETNE && isNullConstant(N1) && 4023 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 4024 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 4025 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 4026 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 4027 if (DAG.MaskedValueIsZero(N0, UpperBits)) 4028 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 4029 } 4030 4031 // Try to eliminate a power-of-2 mask constant by converting to a signbit 4032 // test in a narrow type that we can truncate to with no cost. Examples: 4033 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0 4034 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0 4035 // TODO: This conservatively checks for type legality on the source and 4036 // destination types. That may inhibit optimizations, but it also 4037 // allows setcc->shift transforms that may be more beneficial. 4038 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4039 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() && 4040 isTypeLegal(OpVT) && N0.hasOneUse()) { 4041 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), 4042 AndC->getAPIntValue().getActiveBits()); 4043 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) { 4044 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT); 4045 SDValue Zero = DAG.getConstant(0, DL, NarrowVT); 4046 return DAG.getSetCC(DL, VT, Trunc, Zero, 4047 Cond == ISD::SETEQ ? ISD::SETGE : ISD::SETLT); 4048 } 4049 } 4050 4051 // Match these patterns in any of their permutations: 4052 // (X & Y) == Y 4053 // (X & Y) != Y 4054 SDValue X, Y; 4055 if (N0.getOperand(0) == N1) { 4056 X = N0.getOperand(1); 4057 Y = N0.getOperand(0); 4058 } else if (N0.getOperand(1) == N1) { 4059 X = N0.getOperand(0); 4060 Y = N0.getOperand(1); 4061 } else { 4062 return SDValue(); 4063 } 4064 4065 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if 4066 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as 4067 // its liable to create and infinite loop. 4068 SDValue Zero = DAG.getConstant(0, DL, OpVT); 4069 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) && 4070 DAG.isKnownToBeAPowerOfTwo(Y)) { 4071 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 4072 // Note that where Y is variable and is known to have at most one bit set 4073 // (for example, if it is Z & 1) we cannot do this; the expressions are not 4074 // equivalent when Y == 0. 4075 assert(OpVT.isInteger()); 4076 Cond = ISD::getSetCCInverse(Cond, OpVT); 4077 if (DCI.isBeforeLegalizeOps() || 4078 isCondCodeLegal(Cond, N0.getSimpleValueType())) 4079 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 4080 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 4081 // If the target supports an 'and-not' or 'and-complement' logic operation, 4082 // try to use that to make a comparison operation more efficient. 4083 // But don't do this transform if the mask is a single bit because there are 4084 // more efficient ways to deal with that case (for example, 'bt' on x86 or 4085 // 'rlwinm' on PPC). 4086 4087 // Bail out if the compare operand that we want to turn into a zero is 4088 // already a zero (otherwise, infinite loop). 4089 if (isNullConstant(Y)) 4090 return SDValue(); 4091 4092 // Transform this into: ~X & Y == 0. 4093 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 4094 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 4095 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 4096 } 4097 4098 return SDValue(); 4099 } 4100 4101 /// There are multiple IR patterns that could be checking whether certain 4102 /// truncation of a signed number would be lossy or not. The pattern which is 4103 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 4104 /// We are looking for the following pattern: (KeptBits is a constant) 4105 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 4106 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 4107 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 4108 /// We will unfold it into the natural trunc+sext pattern: 4109 /// ((%x << C) a>> C) dstcond %x 4110 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 4111 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 4112 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 4113 const SDLoc &DL) const { 4114 // We must be comparing with a constant. 4115 ConstantSDNode *C1; 4116 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 4117 return SDValue(); 4118 4119 // N0 should be: add %x, (1 << (KeptBits-1)) 4120 if (N0->getOpcode() != ISD::ADD) 4121 return SDValue(); 4122 4123 // And we must be 'add'ing a constant. 4124 ConstantSDNode *C01; 4125 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 4126 return SDValue(); 4127 4128 SDValue X = N0->getOperand(0); 4129 EVT XVT = X.getValueType(); 4130 4131 // Validate constants ... 4132 4133 APInt I1 = C1->getAPIntValue(); 4134 4135 ISD::CondCode NewCond; 4136 if (Cond == ISD::CondCode::SETULT) { 4137 NewCond = ISD::CondCode::SETEQ; 4138 } else if (Cond == ISD::CondCode::SETULE) { 4139 NewCond = ISD::CondCode::SETEQ; 4140 // But need to 'canonicalize' the constant. 4141 I1 += 1; 4142 } else if (Cond == ISD::CondCode::SETUGT) { 4143 NewCond = ISD::CondCode::SETNE; 4144 // But need to 'canonicalize' the constant. 4145 I1 += 1; 4146 } else if (Cond == ISD::CondCode::SETUGE) { 4147 NewCond = ISD::CondCode::SETNE; 4148 } else 4149 return SDValue(); 4150 4151 APInt I01 = C01->getAPIntValue(); 4152 4153 auto checkConstants = [&I1, &I01]() -> bool { 4154 // Both of them must be power-of-two, and the constant from setcc is bigger. 4155 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 4156 }; 4157 4158 if (checkConstants()) { 4159 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 4160 } else { 4161 // What if we invert constants? (and the target predicate) 4162 I1.negate(); 4163 I01.negate(); 4164 assert(XVT.isInteger()); 4165 NewCond = getSetCCInverse(NewCond, XVT); 4166 if (!checkConstants()) 4167 return SDValue(); 4168 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 4169 } 4170 4171 // They are power-of-two, so which bit is set? 4172 const unsigned KeptBits = I1.logBase2(); 4173 const unsigned KeptBitsMinusOne = I01.logBase2(); 4174 4175 // Magic! 4176 if (KeptBits != (KeptBitsMinusOne + 1)) 4177 return SDValue(); 4178 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 4179 4180 // We don't want to do this in every single case. 4181 SelectionDAG &DAG = DCI.DAG; 4182 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits)) 4183 return SDValue(); 4184 4185 // Unfold into: sext_inreg(%x) cond %x 4186 // Where 'cond' will be either 'eq' or 'ne'. 4187 SDValue SExtInReg = DAG.getNode( 4188 ISD::SIGN_EXTEND_INREG, DL, XVT, X, 4189 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits))); 4190 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond); 4191 } 4192 4193 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4194 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 4195 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 4196 DAGCombinerInfo &DCI, const SDLoc &DL) const { 4197 assert(isConstOrConstSplat(N1C) && isConstOrConstSplat(N1C)->isZero() && 4198 "Should be a comparison with 0."); 4199 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4200 "Valid only for [in]equality comparisons."); 4201 4202 unsigned NewShiftOpcode; 4203 SDValue X, C, Y; 4204 4205 SelectionDAG &DAG = DCI.DAG; 4206 4207 // Look for '(C l>>/<< Y)'. 4208 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) { 4209 // The shift should be one-use. 4210 if (!V.hasOneUse()) 4211 return false; 4212 unsigned OldShiftOpcode = V.getOpcode(); 4213 switch (OldShiftOpcode) { 4214 case ISD::SHL: 4215 NewShiftOpcode = ISD::SRL; 4216 break; 4217 case ISD::SRL: 4218 NewShiftOpcode = ISD::SHL; 4219 break; 4220 default: 4221 return false; // must be a logical shift. 4222 } 4223 // We should be shifting a constant. 4224 // FIXME: best to use isConstantOrConstantVector(). 4225 C = V.getOperand(0); 4226 ConstantSDNode *CC = 4227 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4228 if (!CC) 4229 return false; 4230 Y = V.getOperand(1); 4231 4232 ConstantSDNode *XC = 4233 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4234 return shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 4235 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 4236 }; 4237 4238 // LHS of comparison should be an one-use 'and'. 4239 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 4240 return SDValue(); 4241 4242 X = N0.getOperand(0); 4243 SDValue Mask = N0.getOperand(1); 4244 4245 // 'and' is commutative! 4246 if (!Match(Mask)) { 4247 std::swap(X, Mask); 4248 if (!Match(Mask)) 4249 return SDValue(); 4250 } 4251 4252 EVT VT = X.getValueType(); 4253 4254 // Produce: 4255 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 4256 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 4257 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 4258 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 4259 return T2; 4260 } 4261 4262 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 4263 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 4264 /// handle the commuted versions of these patterns. 4265 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 4266 ISD::CondCode Cond, const SDLoc &DL, 4267 DAGCombinerInfo &DCI) const { 4268 unsigned BOpcode = N0.getOpcode(); 4269 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 4270 "Unexpected binop"); 4271 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 4272 4273 // (X + Y) == X --> Y == 0 4274 // (X - Y) == X --> Y == 0 4275 // (X ^ Y) == X --> Y == 0 4276 SelectionDAG &DAG = DCI.DAG; 4277 EVT OpVT = N0.getValueType(); 4278 SDValue X = N0.getOperand(0); 4279 SDValue Y = N0.getOperand(1); 4280 if (X == N1) 4281 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 4282 4283 if (Y != N1) 4284 return SDValue(); 4285 4286 // (X + Y) == Y --> X == 0 4287 // (X ^ Y) == Y --> X == 0 4288 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 4289 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 4290 4291 // The shift would not be valid if the operands are boolean (i1). 4292 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 4293 return SDValue(); 4294 4295 // (X - Y) == Y --> X == Y << 1 4296 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL); 4297 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 4298 if (!DCI.isCalledByLegalizer()) 4299 DCI.AddToWorklist(YShl1.getNode()); 4300 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 4301 } 4302 4303 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 4304 SDValue N0, const APInt &C1, 4305 ISD::CondCode Cond, const SDLoc &dl, 4306 SelectionDAG &DAG) { 4307 // Look through truncs that don't change the value of a ctpop. 4308 // FIXME: Add vector support? Need to be careful with setcc result type below. 4309 SDValue CTPOP = N0; 4310 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 4311 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 4312 CTPOP = N0.getOperand(0); 4313 4314 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 4315 return SDValue(); 4316 4317 EVT CTVT = CTPOP.getValueType(); 4318 SDValue CTOp = CTPOP.getOperand(0); 4319 4320 // Expand a power-of-2-or-zero comparison based on ctpop: 4321 // (ctpop x) u< 2 -> (x & x-1) == 0 4322 // (ctpop x) u> 1 -> (x & x-1) != 0 4323 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 4324 // Keep the CTPOP if it is a cheap vector op. 4325 if (CTVT.isVector() && TLI.isCtpopFast(CTVT)) 4326 return SDValue(); 4327 4328 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 4329 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 4330 return SDValue(); 4331 if (C1 == 0 && (Cond == ISD::SETULT)) 4332 return SDValue(); // This is handled elsewhere. 4333 4334 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 4335 4336 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4337 SDValue Result = CTOp; 4338 for (unsigned i = 0; i < Passes; i++) { 4339 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 4340 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 4341 } 4342 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 4343 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 4344 } 4345 4346 // Expand a power-of-2 comparison based on ctpop 4347 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 4348 // Keep the CTPOP if it is cheap. 4349 if (TLI.isCtpopFast(CTVT)) 4350 return SDValue(); 4351 4352 SDValue Zero = DAG.getConstant(0, dl, CTVT); 4353 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4354 assert(CTVT.isInteger()); 4355 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 4356 4357 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so 4358 // check before emitting a potentially unnecessary op. 4359 if (DAG.isKnownNeverZero(CTOp)) { 4360 // (ctpop x) == 1 --> (x & x-1) == 0 4361 // (ctpop x) != 1 --> (x & x-1) != 0 4362 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 4363 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 4364 return RHS; 4365 } 4366 4367 // (ctpop x) == 1 --> (x ^ x-1) > x-1 4368 // (ctpop x) != 1 --> (x ^ x-1) <= x-1 4369 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add); 4370 ISD::CondCode CmpCond = Cond == ISD::SETEQ ? ISD::SETUGT : ISD::SETULE; 4371 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond); 4372 } 4373 4374 return SDValue(); 4375 } 4376 4377 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 4378 ISD::CondCode Cond, const SDLoc &dl, 4379 SelectionDAG &DAG) { 4380 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4381 return SDValue(); 4382 4383 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4384 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 4385 return SDValue(); 4386 4387 auto getRotateSource = [](SDValue X) { 4388 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 4389 return X.getOperand(0); 4390 return SDValue(); 4391 }; 4392 4393 // Peek through a rotated value compared against 0 or -1: 4394 // (rot X, Y) == 0/-1 --> X == 0/-1 4395 // (rot X, Y) != 0/-1 --> X != 0/-1 4396 if (SDValue R = getRotateSource(N0)) 4397 return DAG.getSetCC(dl, VT, R, N1, Cond); 4398 4399 // Peek through an 'or' of a rotated value compared against 0: 4400 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 4401 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 4402 // 4403 // TODO: Add the 'and' with -1 sibling. 4404 // TODO: Recurse through a series of 'or' ops to find the rotate. 4405 EVT OpVT = N0.getValueType(); 4406 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 4407 if (SDValue R = getRotateSource(N0.getOperand(0))) { 4408 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 4409 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4410 } 4411 if (SDValue R = getRotateSource(N0.getOperand(1))) { 4412 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 4413 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4414 } 4415 } 4416 4417 return SDValue(); 4418 } 4419 4420 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 4421 ISD::CondCode Cond, const SDLoc &dl, 4422 SelectionDAG &DAG) { 4423 // If we are testing for all-bits-clear, we might be able to do that with 4424 // less shifting since bit-order does not matter. 4425 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4426 return SDValue(); 4427 4428 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4429 if (!C1 || !C1->isZero()) 4430 return SDValue(); 4431 4432 if (!N0.hasOneUse() || 4433 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4434 return SDValue(); 4435 4436 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4437 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4438 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4439 return SDValue(); 4440 4441 // Canonicalize fshr as fshl to reduce pattern-matching. 4442 unsigned ShAmt = ShAmtC->getZExtValue(); 4443 if (N0.getOpcode() == ISD::FSHR) 4444 ShAmt = BitWidth - ShAmt; 4445 4446 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4447 SDValue X, Y; 4448 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4449 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4450 return false; 4451 if (Or.getOperand(0) == Other) { 4452 X = Or.getOperand(0); 4453 Y = Or.getOperand(1); 4454 return true; 4455 } 4456 if (Or.getOperand(1) == Other) { 4457 X = Or.getOperand(1); 4458 Y = Or.getOperand(0); 4459 return true; 4460 } 4461 return false; 4462 }; 4463 4464 EVT OpVT = N0.getValueType(); 4465 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4466 SDValue F0 = N0.getOperand(0); 4467 SDValue F1 = N0.getOperand(1); 4468 if (matchOr(F0, F1)) { 4469 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4470 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4471 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4472 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4473 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4474 } 4475 if (matchOr(F1, F0)) { 4476 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4477 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4478 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4479 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4480 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4481 } 4482 4483 return SDValue(); 4484 } 4485 4486 /// Try to simplify a setcc built with the specified operands and cc. If it is 4487 /// unable to simplify it, return a null SDValue. 4488 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4489 ISD::CondCode Cond, bool foldBooleans, 4490 DAGCombinerInfo &DCI, 4491 const SDLoc &dl) const { 4492 SelectionDAG &DAG = DCI.DAG; 4493 const DataLayout &Layout = DAG.getDataLayout(); 4494 EVT OpVT = N0.getValueType(); 4495 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4496 4497 // Constant fold or commute setcc. 4498 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4499 return Fold; 4500 4501 bool N0ConstOrSplat = 4502 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4503 bool N1ConstOrSplat = 4504 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4505 4506 // Canonicalize toward having the constant on the RHS. 4507 // TODO: Handle non-splat vector constants. All undef causes trouble. 4508 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4509 // infinite loop here when we encounter one. 4510 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4511 if (N0ConstOrSplat && !N1ConstOrSplat && 4512 (DCI.isBeforeLegalizeOps() || 4513 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4514 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4515 4516 // If we have a subtract with the same 2 non-constant operands as this setcc 4517 // -- but in reverse order -- then try to commute the operands of this setcc 4518 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4519 // instruction on some targets. 4520 if (!N0ConstOrSplat && !N1ConstOrSplat && 4521 (DCI.isBeforeLegalizeOps() || 4522 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4523 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4524 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4525 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4526 4527 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4528 return V; 4529 4530 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4531 return V; 4532 4533 if (auto *N1C = isConstOrConstSplat(N1)) { 4534 const APInt &C1 = N1C->getAPIntValue(); 4535 4536 // Optimize some CTPOP cases. 4537 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4538 return V; 4539 4540 // For equality to 0 of a no-wrap multiply, decompose and test each op: 4541 // X * Y == 0 --> (X == 0) || (Y == 0) 4542 // X * Y != 0 --> (X != 0) && (Y != 0) 4543 // TODO: This bails out if minsize is set, but if the target doesn't have a 4544 // single instruction multiply for this type, it would likely be 4545 // smaller to decompose. 4546 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4547 N0.getOpcode() == ISD::MUL && N0.hasOneUse() && 4548 (N0->getFlags().hasNoUnsignedWrap() || 4549 N0->getFlags().hasNoSignedWrap()) && 4550 !Attr.hasFnAttr(Attribute::MinSize)) { 4551 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4552 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond); 4553 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND; 4554 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero); 4555 } 4556 4557 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4558 // equality comparison, then we're just comparing whether X itself is 4559 // zero. 4560 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4561 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4562 llvm::has_single_bit<uint32_t>(N0.getScalarValueSizeInBits())) { 4563 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4564 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4565 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4566 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4567 // (srl (ctlz x), 5) == 0 -> X != 0 4568 // (srl (ctlz x), 5) != 1 -> X != 0 4569 Cond = ISD::SETNE; 4570 } else { 4571 // (srl (ctlz x), 5) != 0 -> X == 0 4572 // (srl (ctlz x), 5) == 1 -> X == 0 4573 Cond = ISD::SETEQ; 4574 } 4575 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4576 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4577 Cond); 4578 } 4579 } 4580 } 4581 } 4582 4583 // FIXME: Support vectors. 4584 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4585 const APInt &C1 = N1C->getAPIntValue(); 4586 4587 // (zext x) == C --> x == (trunc C) 4588 // (sext x) == C --> x == (trunc C) 4589 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4590 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4591 unsigned MinBits = N0.getValueSizeInBits(); 4592 SDValue PreExt; 4593 bool Signed = false; 4594 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4595 // ZExt 4596 MinBits = N0->getOperand(0).getValueSizeInBits(); 4597 PreExt = N0->getOperand(0); 4598 } else if (N0->getOpcode() == ISD::AND) { 4599 // DAGCombine turns costly ZExts into ANDs 4600 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4601 if ((C->getAPIntValue()+1).isPowerOf2()) { 4602 MinBits = C->getAPIntValue().countr_one(); 4603 PreExt = N0->getOperand(0); 4604 } 4605 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4606 // SExt 4607 MinBits = N0->getOperand(0).getValueSizeInBits(); 4608 PreExt = N0->getOperand(0); 4609 Signed = true; 4610 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4611 // ZEXTLOAD / SEXTLOAD 4612 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4613 MinBits = LN0->getMemoryVT().getSizeInBits(); 4614 PreExt = N0; 4615 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4616 Signed = true; 4617 MinBits = LN0->getMemoryVT().getSizeInBits(); 4618 PreExt = N0; 4619 } 4620 } 4621 4622 // Figure out how many bits we need to preserve this constant. 4623 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits(); 4624 4625 // Make sure we're not losing bits from the constant. 4626 if (MinBits > 0 && 4627 MinBits < C1.getBitWidth() && 4628 MinBits >= ReqdBits) { 4629 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4630 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4631 // Will get folded away. 4632 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4633 if (MinBits == 1 && C1 == 1) 4634 // Invert the condition. 4635 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4636 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4637 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4638 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4639 } 4640 4641 // If truncating the setcc operands is not desirable, we can still 4642 // simplify the expression in some cases: 4643 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4644 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4645 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4646 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4647 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4648 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4649 SDValue TopSetCC = N0->getOperand(0); 4650 unsigned N0Opc = N0->getOpcode(); 4651 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4652 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4653 TopSetCC.getOpcode() == ISD::SETCC && 4654 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4655 (isConstFalseVal(N1) || 4656 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4657 4658 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4659 (!N1C->isZero() && Cond == ISD::SETNE); 4660 4661 if (!Inverse) 4662 return TopSetCC; 4663 4664 ISD::CondCode InvCond = ISD::getSetCCInverse( 4665 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4666 TopSetCC.getOperand(0).getValueType()); 4667 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4668 TopSetCC.getOperand(1), 4669 InvCond); 4670 } 4671 } 4672 } 4673 4674 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4675 // equality or unsigned, and all 1 bits of the const are in the same 4676 // partial word, see if we can shorten the load. 4677 if (DCI.isBeforeLegalize() && 4678 !ISD::isSignedIntSetCC(Cond) && 4679 N0.getOpcode() == ISD::AND && C1 == 0 && 4680 N0.getNode()->hasOneUse() && 4681 isa<LoadSDNode>(N0.getOperand(0)) && 4682 N0.getOperand(0).getNode()->hasOneUse() && 4683 isa<ConstantSDNode>(N0.getOperand(1))) { 4684 auto *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4685 APInt bestMask; 4686 unsigned bestWidth = 0, bestOffset = 0; 4687 if (Lod->isSimple() && Lod->isUnindexed() && 4688 (Lod->getMemoryVT().isByteSized() || 4689 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) { 4690 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits(); 4691 unsigned origWidth = N0.getValueSizeInBits(); 4692 unsigned maskWidth = origWidth; 4693 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4694 // 8 bits, but have to be careful... 4695 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4696 origWidth = Lod->getMemoryVT().getSizeInBits(); 4697 const APInt &Mask = N0.getConstantOperandAPInt(1); 4698 // Only consider power-of-2 widths (and at least one byte) as candiates 4699 // for the narrowed load. 4700 for (unsigned width = 8; width < origWidth; width *= 2) { 4701 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width); 4702 if (!shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) 4703 continue; 4704 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4705 // Avoid accessing any padding here for now (we could use memWidth 4706 // instead of origWidth here otherwise). 4707 unsigned maxOffset = origWidth - width; 4708 for (unsigned offset = 0; offset <= maxOffset; offset += 8) { 4709 if (Mask.isSubsetOf(newMask)) { 4710 unsigned ptrOffset = 4711 Layout.isLittleEndian() ? offset : memWidth - width - offset; 4712 unsigned IsFast = 0; 4713 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8); 4714 if (allowsMemoryAccess( 4715 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(), 4716 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) && 4717 IsFast) { 4718 bestOffset = ptrOffset / 8; 4719 bestMask = Mask.lshr(offset); 4720 bestWidth = width; 4721 break; 4722 } 4723 } 4724 newMask <<= 8; 4725 } 4726 if (bestWidth) 4727 break; 4728 } 4729 } 4730 if (bestWidth) { 4731 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4732 SDValue Ptr = Lod->getBasePtr(); 4733 if (bestOffset != 0) 4734 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset)); 4735 SDValue NewLoad = 4736 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4737 Lod->getPointerInfo().getWithOffset(bestOffset), 4738 Lod->getOriginalAlign()); 4739 SDValue And = 4740 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4741 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT)); 4742 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond); 4743 } 4744 } 4745 4746 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4747 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4748 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4749 4750 // If the comparison constant has bits in the upper part, the 4751 // zero-extended value could never match. 4752 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4753 C1.getBitWidth() - InSize))) { 4754 switch (Cond) { 4755 case ISD::SETUGT: 4756 case ISD::SETUGE: 4757 case ISD::SETEQ: 4758 return DAG.getConstant(0, dl, VT); 4759 case ISD::SETULT: 4760 case ISD::SETULE: 4761 case ISD::SETNE: 4762 return DAG.getConstant(1, dl, VT); 4763 case ISD::SETGT: 4764 case ISD::SETGE: 4765 // True if the sign bit of C1 is set. 4766 return DAG.getConstant(C1.isNegative(), dl, VT); 4767 case ISD::SETLT: 4768 case ISD::SETLE: 4769 // True if the sign bit of C1 isn't set. 4770 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4771 default: 4772 break; 4773 } 4774 } 4775 4776 // Otherwise, we can perform the comparison with the low bits. 4777 switch (Cond) { 4778 case ISD::SETEQ: 4779 case ISD::SETNE: 4780 case ISD::SETUGT: 4781 case ISD::SETUGE: 4782 case ISD::SETULT: 4783 case ISD::SETULE: { 4784 EVT newVT = N0.getOperand(0).getValueType(); 4785 // FIXME: Should use isNarrowingProfitable. 4786 if (DCI.isBeforeLegalizeOps() || 4787 (isOperationLegal(ISD::SETCC, newVT) && 4788 isCondCodeLegal(Cond, newVT.getSimpleVT()) && 4789 isTypeDesirableForOp(ISD::SETCC, newVT))) { 4790 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4791 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4792 4793 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4794 NewConst, Cond); 4795 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4796 } 4797 break; 4798 } 4799 default: 4800 break; // todo, be more careful with signed comparisons 4801 } 4802 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4803 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4804 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4805 OpVT)) { 4806 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4807 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4808 EVT ExtDstTy = N0.getValueType(); 4809 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4810 4811 // If the constant doesn't fit into the number of bits for the source of 4812 // the sign extension, it is impossible for both sides to be equal. 4813 if (C1.getSignificantBits() > ExtSrcTyBits) 4814 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4815 4816 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4817 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4818 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4819 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4820 DAG.getConstant(Imm, dl, ExtDstTy)); 4821 if (!DCI.isCalledByLegalizer()) 4822 DCI.AddToWorklist(ZextOp.getNode()); 4823 // Otherwise, make this a use of a zext. 4824 return DAG.getSetCC(dl, VT, ZextOp, 4825 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4826 } else if ((N1C->isZero() || N1C->isOne()) && 4827 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4828 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are 4829 // excluded as they are handled below whilst checking for foldBooleans. 4830 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) && 4831 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4832 (N0.getValueType() == MVT::i1 || 4833 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4834 DAG.MaskedValueIsZero( 4835 N0, APInt::getBitsSetFrom(N0.getValueSizeInBits(), 1))) { 4836 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4837 if (TrueWhenTrue) 4838 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4839 // Invert the condition. 4840 if (N0.getOpcode() == ISD::SETCC) { 4841 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4842 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4843 if (DCI.isBeforeLegalizeOps() || 4844 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4845 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4846 } 4847 } 4848 4849 if ((N0.getOpcode() == ISD::XOR || 4850 (N0.getOpcode() == ISD::AND && 4851 N0.getOperand(0).getOpcode() == ISD::XOR && 4852 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4853 isOneConstant(N0.getOperand(1))) { 4854 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4855 // can only do this if the top bits are known zero. 4856 unsigned BitWidth = N0.getValueSizeInBits(); 4857 if (DAG.MaskedValueIsZero(N0, 4858 APInt::getHighBitsSet(BitWidth, 4859 BitWidth-1))) { 4860 // Okay, get the un-inverted input value. 4861 SDValue Val; 4862 if (N0.getOpcode() == ISD::XOR) { 4863 Val = N0.getOperand(0); 4864 } else { 4865 assert(N0.getOpcode() == ISD::AND && 4866 N0.getOperand(0).getOpcode() == ISD::XOR); 4867 // ((X^1)&1)^1 -> X & 1 4868 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4869 N0.getOperand(0).getOperand(0), 4870 N0.getOperand(1)); 4871 } 4872 4873 return DAG.getSetCC(dl, VT, Val, N1, 4874 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4875 } 4876 } else if (N1C->isOne()) { 4877 SDValue Op0 = N0; 4878 if (Op0.getOpcode() == ISD::TRUNCATE) 4879 Op0 = Op0.getOperand(0); 4880 4881 if ((Op0.getOpcode() == ISD::XOR) && 4882 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4883 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4884 SDValue XorLHS = Op0.getOperand(0); 4885 SDValue XorRHS = Op0.getOperand(1); 4886 // Ensure that the input setccs return an i1 type or 0/1 value. 4887 if (Op0.getValueType() == MVT::i1 || 4888 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4889 ZeroOrOneBooleanContent && 4890 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4891 ZeroOrOneBooleanContent)) { 4892 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4893 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4894 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4895 } 4896 } 4897 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4898 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4899 if (Op0.getValueType().bitsGT(VT)) 4900 Op0 = DAG.getNode(ISD::AND, dl, VT, 4901 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4902 DAG.getConstant(1, dl, VT)); 4903 else if (Op0.getValueType().bitsLT(VT)) 4904 Op0 = DAG.getNode(ISD::AND, dl, VT, 4905 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4906 DAG.getConstant(1, dl, VT)); 4907 4908 return DAG.getSetCC(dl, VT, Op0, 4909 DAG.getConstant(0, dl, Op0.getValueType()), 4910 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4911 } 4912 if (Op0.getOpcode() == ISD::AssertZext && 4913 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4914 return DAG.getSetCC(dl, VT, Op0, 4915 DAG.getConstant(0, dl, Op0.getValueType()), 4916 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4917 } 4918 } 4919 4920 // Given: 4921 // icmp eq/ne (urem %x, %y), 0 4922 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4923 // icmp eq/ne %x, 0 4924 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4925 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4926 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4927 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4928 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4929 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4930 } 4931 4932 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4933 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4934 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4935 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4936 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4937 N1C->isAllOnes()) { 4938 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4939 DAG.getConstant(0, dl, OpVT), 4940 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4941 } 4942 4943 if (SDValue V = 4944 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4945 return V; 4946 } 4947 4948 // These simplifications apply to splat vectors as well. 4949 // TODO: Handle more splat vector cases. 4950 if (auto *N1C = isConstOrConstSplat(N1)) { 4951 const APInt &C1 = N1C->getAPIntValue(); 4952 4953 APInt MinVal, MaxVal; 4954 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4955 if (ISD::isSignedIntSetCC(Cond)) { 4956 MinVal = APInt::getSignedMinValue(OperandBitSize); 4957 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4958 } else { 4959 MinVal = APInt::getMinValue(OperandBitSize); 4960 MaxVal = APInt::getMaxValue(OperandBitSize); 4961 } 4962 4963 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4964 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4965 // X >= MIN --> true 4966 if (C1 == MinVal) 4967 return DAG.getBoolConstant(true, dl, VT, OpVT); 4968 4969 if (!VT.isVector()) { // TODO: Support this for vectors. 4970 // X >= C0 --> X > (C0 - 1) 4971 APInt C = C1 - 1; 4972 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4973 if ((DCI.isBeforeLegalizeOps() || 4974 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4975 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4976 isLegalICmpImmediate(C.getSExtValue())))) { 4977 return DAG.getSetCC(dl, VT, N0, 4978 DAG.getConstant(C, dl, N1.getValueType()), 4979 NewCC); 4980 } 4981 } 4982 } 4983 4984 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4985 // X <= MAX --> true 4986 if (C1 == MaxVal) 4987 return DAG.getBoolConstant(true, dl, VT, OpVT); 4988 4989 // X <= C0 --> X < (C0 + 1) 4990 if (!VT.isVector()) { // TODO: Support this for vectors. 4991 APInt C = C1 + 1; 4992 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4993 if ((DCI.isBeforeLegalizeOps() || 4994 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4995 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4996 isLegalICmpImmediate(C.getSExtValue())))) { 4997 return DAG.getSetCC(dl, VT, N0, 4998 DAG.getConstant(C, dl, N1.getValueType()), 4999 NewCC); 5000 } 5001 } 5002 } 5003 5004 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 5005 if (C1 == MinVal) 5006 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 5007 5008 // TODO: Support this for vectors after legalize ops. 5009 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 5010 // Canonicalize setlt X, Max --> setne X, Max 5011 if (C1 == MaxVal) 5012 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 5013 5014 // If we have setult X, 1, turn it into seteq X, 0 5015 if (C1 == MinVal+1) 5016 return DAG.getSetCC(dl, VT, N0, 5017 DAG.getConstant(MinVal, dl, N0.getValueType()), 5018 ISD::SETEQ); 5019 } 5020 } 5021 5022 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 5023 if (C1 == MaxVal) 5024 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 5025 5026 // TODO: Support this for vectors after legalize ops. 5027 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 5028 // Canonicalize setgt X, Min --> setne X, Min 5029 if (C1 == MinVal) 5030 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 5031 5032 // If we have setugt X, Max-1, turn it into seteq X, Max 5033 if (C1 == MaxVal-1) 5034 return DAG.getSetCC(dl, VT, N0, 5035 DAG.getConstant(MaxVal, dl, N0.getValueType()), 5036 ISD::SETEQ); 5037 } 5038 } 5039 5040 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 5041 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 5042 if (C1.isZero()) 5043 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 5044 VT, N0, N1, Cond, DCI, dl)) 5045 return CC; 5046 5047 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 5048 // For example, when high 32-bits of i64 X are known clear: 5049 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 5050 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 5051 bool CmpZero = N1C->isZero(); 5052 bool CmpNegOne = N1C->isAllOnes(); 5053 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 5054 // Match or(lo,shl(hi,bw/2)) pattern. 5055 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 5056 unsigned EltBits = V.getScalarValueSizeInBits(); 5057 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 5058 return false; 5059 SDValue LHS = V.getOperand(0); 5060 SDValue RHS = V.getOperand(1); 5061 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 5062 // Unshifted element must have zero upperbits. 5063 if (RHS.getOpcode() == ISD::SHL && 5064 isa<ConstantSDNode>(RHS.getOperand(1)) && 5065 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 5066 DAG.MaskedValueIsZero(LHS, HiBits)) { 5067 Lo = LHS; 5068 Hi = RHS.getOperand(0); 5069 return true; 5070 } 5071 if (LHS.getOpcode() == ISD::SHL && 5072 isa<ConstantSDNode>(LHS.getOperand(1)) && 5073 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 5074 DAG.MaskedValueIsZero(RHS, HiBits)) { 5075 Lo = RHS; 5076 Hi = LHS.getOperand(0); 5077 return true; 5078 } 5079 return false; 5080 }; 5081 5082 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 5083 unsigned EltBits = N0.getScalarValueSizeInBits(); 5084 unsigned HalfBits = EltBits / 2; 5085 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 5086 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 5087 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 5088 SDValue NewN0 = 5089 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 5090 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 5091 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 5092 }; 5093 5094 SDValue Lo, Hi; 5095 if (IsConcat(N0, Lo, Hi)) 5096 return MergeConcat(Lo, Hi); 5097 5098 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 5099 SDValue Lo0, Lo1, Hi0, Hi1; 5100 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 5101 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 5102 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 5103 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 5104 } 5105 } 5106 } 5107 } 5108 5109 // If we have "setcc X, C0", check to see if we can shrink the immediate 5110 // by changing cc. 5111 // TODO: Support this for vectors after legalize ops. 5112 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 5113 // SETUGT X, SINTMAX -> SETLT X, 0 5114 // SETUGE X, SINTMIN -> SETLT X, 0 5115 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 5116 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 5117 return DAG.getSetCC(dl, VT, N0, 5118 DAG.getConstant(0, dl, N1.getValueType()), 5119 ISD::SETLT); 5120 5121 // SETULT X, SINTMIN -> SETGT X, -1 5122 // SETULE X, SINTMAX -> SETGT X, -1 5123 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 5124 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 5125 return DAG.getSetCC(dl, VT, N0, 5126 DAG.getAllOnesConstant(dl, N1.getValueType()), 5127 ISD::SETGT); 5128 } 5129 } 5130 5131 // Back to non-vector simplifications. 5132 // TODO: Can we do these for vector splats? 5133 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 5134 const APInt &C1 = N1C->getAPIntValue(); 5135 EVT ShValTy = N0.getValueType(); 5136 5137 // Fold bit comparisons when we can. This will result in an 5138 // incorrect value when boolean false is negative one, unless 5139 // the bitsize is 1 in which case the false value is the same 5140 // in practice regardless of the representation. 5141 if ((VT.getSizeInBits() == 1 || 5142 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 5143 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5144 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 5145 N0.getOpcode() == ISD::AND) { 5146 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5147 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 5148 // Perform the xform if the AND RHS is a single bit. 5149 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 5150 if (AndRHS->getAPIntValue().isPowerOf2() && 5151 !shouldAvoidTransformToShift(ShValTy, ShCt)) { 5152 return DAG.getNode( 5153 ISD::TRUNCATE, dl, VT, 5154 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5155 DAG.getShiftAmountConstant(ShCt, ShValTy, dl))); 5156 } 5157 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 5158 // (X & 8) == 8 --> (X & 8) >> 3 5159 // Perform the xform if C1 is a single bit. 5160 unsigned ShCt = C1.logBase2(); 5161 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) { 5162 return DAG.getNode( 5163 ISD::TRUNCATE, dl, VT, 5164 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5165 DAG.getShiftAmountConstant(ShCt, ShValTy, dl))); 5166 } 5167 } 5168 } 5169 } 5170 5171 if (C1.getSignificantBits() <= 64 && 5172 !isLegalICmpImmediate(C1.getSExtValue())) { 5173 // (X & -256) == 256 -> (X >> 8) == 1 5174 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5175 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 5176 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5177 const APInt &AndRHSC = AndRHS->getAPIntValue(); 5178 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) { 5179 unsigned ShiftBits = AndRHSC.countr_zero(); 5180 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5181 SDValue Shift = DAG.getNode( 5182 ISD::SRL, dl, ShValTy, N0.getOperand(0), 5183 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl)); 5184 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 5185 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 5186 } 5187 } 5188 } 5189 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 5190 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 5191 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 5192 // X < 0x100000000 -> (X >> 32) < 1 5193 // X >= 0x100000000 -> (X >> 32) >= 1 5194 // X <= 0x0ffffffff -> (X >> 32) < 1 5195 // X > 0x0ffffffff -> (X >> 32) >= 1 5196 unsigned ShiftBits; 5197 APInt NewC = C1; 5198 ISD::CondCode NewCond = Cond; 5199 if (AdjOne) { 5200 ShiftBits = C1.countr_one(); 5201 NewC = NewC + 1; 5202 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 5203 } else { 5204 ShiftBits = C1.countr_zero(); 5205 } 5206 NewC.lshrInPlace(ShiftBits); 5207 if (ShiftBits && NewC.getSignificantBits() <= 64 && 5208 isLegalICmpImmediate(NewC.getSExtValue()) && 5209 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5210 SDValue Shift = 5211 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5212 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl)); 5213 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 5214 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 5215 } 5216 } 5217 } 5218 } 5219 5220 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 5221 auto *CFP = cast<ConstantFPSDNode>(N1); 5222 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 5223 5224 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 5225 // constant if knowing that the operand is non-nan is enough. We prefer to 5226 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 5227 // materialize 0.0. 5228 if (Cond == ISD::SETO || Cond == ISD::SETUO) 5229 return DAG.getSetCC(dl, VT, N0, N0, Cond); 5230 5231 // setcc (fneg x), C -> setcc swap(pred) x, -C 5232 if (N0.getOpcode() == ISD::FNEG) { 5233 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 5234 if (DCI.isBeforeLegalizeOps() || 5235 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 5236 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 5237 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 5238 } 5239 } 5240 5241 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf 5242 if (isOperationLegalOrCustom(ISD::IS_FPCLASS, N0.getValueType()) && 5243 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) { 5244 bool IsFabs = N0.getOpcode() == ISD::FABS; 5245 SDValue Op = IsFabs ? N0.getOperand(0) : N0; 5246 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) { 5247 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf) 5248 : (IsFabs ? fcInf : fcPosInf); 5249 if (Cond == ISD::SETUEQ) 5250 Flag |= fcNan; 5251 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op, 5252 DAG.getTargetConstant(Flag, dl, MVT::i32)); 5253 } 5254 } 5255 5256 // If the condition is not legal, see if we can find an equivalent one 5257 // which is legal. 5258 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 5259 // If the comparison was an awkward floating-point == or != and one of 5260 // the comparison operands is infinity or negative infinity, convert the 5261 // condition to a less-awkward <= or >=. 5262 if (CFP->getValueAPF().isInfinity()) { 5263 bool IsNegInf = CFP->getValueAPF().isNegative(); 5264 ISD::CondCode NewCond = ISD::SETCC_INVALID; 5265 switch (Cond) { 5266 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 5267 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 5268 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 5269 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 5270 default: break; 5271 } 5272 if (NewCond != ISD::SETCC_INVALID && 5273 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 5274 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5275 } 5276 } 5277 } 5278 5279 if (N0 == N1) { 5280 // The sext(setcc()) => setcc() optimization relies on the appropriate 5281 // constant being emitted. 5282 assert(!N0.getValueType().isInteger() && 5283 "Integer types should be handled by FoldSetCC"); 5284 5285 bool EqTrue = ISD::isTrueWhenEqual(Cond); 5286 unsigned UOF = ISD::getUnorderedFlavor(Cond); 5287 if (UOF == 2) // FP operators that are undefined on NaNs. 5288 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5289 if (UOF == unsigned(EqTrue)) 5290 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5291 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 5292 // if it is not already. 5293 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 5294 if (NewCond != Cond && 5295 (DCI.isBeforeLegalizeOps() || 5296 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 5297 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5298 } 5299 5300 // ~X > ~Y --> Y > X 5301 // ~X < ~Y --> Y < X 5302 // ~X < C --> X > ~C 5303 // ~X > C --> X < ~C 5304 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) && 5305 N0.getValueType().isInteger()) { 5306 if (isBitwiseNot(N0)) { 5307 if (isBitwiseNot(N1)) 5308 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond); 5309 5310 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 5311 !DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(0))) { 5312 SDValue Not = DAG.getNOT(dl, N1, OpVT); 5313 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond); 5314 } 5315 } 5316 } 5317 5318 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5319 N0.getValueType().isInteger()) { 5320 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 5321 N0.getOpcode() == ISD::XOR) { 5322 // Simplify (X+Y) == (X+Z) --> Y == Z 5323 if (N0.getOpcode() == N1.getOpcode()) { 5324 if (N0.getOperand(0) == N1.getOperand(0)) 5325 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 5326 if (N0.getOperand(1) == N1.getOperand(1)) 5327 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 5328 if (isCommutativeBinOp(N0.getOpcode())) { 5329 // If X op Y == Y op X, try other combinations. 5330 if (N0.getOperand(0) == N1.getOperand(1)) 5331 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 5332 Cond); 5333 if (N0.getOperand(1) == N1.getOperand(0)) 5334 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 5335 Cond); 5336 } 5337 } 5338 5339 // If RHS is a legal immediate value for a compare instruction, we need 5340 // to be careful about increasing register pressure needlessly. 5341 bool LegalRHSImm = false; 5342 5343 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 5344 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5345 // Turn (X+C1) == C2 --> X == C2-C1 5346 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 5347 return DAG.getSetCC( 5348 dl, VT, N0.getOperand(0), 5349 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 5350 dl, N0.getValueType()), 5351 Cond); 5352 5353 // Turn (X^C1) == C2 --> X == C1^C2 5354 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 5355 return DAG.getSetCC( 5356 dl, VT, N0.getOperand(0), 5357 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 5358 dl, N0.getValueType()), 5359 Cond); 5360 } 5361 5362 // Turn (C1-X) == C2 --> X == C1-C2 5363 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 5364 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 5365 return DAG.getSetCC( 5366 dl, VT, N0.getOperand(1), 5367 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 5368 dl, N0.getValueType()), 5369 Cond); 5370 5371 // Could RHSC fold directly into a compare? 5372 if (RHSC->getValueType(0).getSizeInBits() <= 64) 5373 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 5374 } 5375 5376 // (X+Y) == X --> Y == 0 and similar folds. 5377 // Don't do this if X is an immediate that can fold into a cmp 5378 // instruction and X+Y has other uses. It could be an induction variable 5379 // chain, and the transform would increase register pressure. 5380 if (!LegalRHSImm || N0.hasOneUse()) 5381 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 5382 return V; 5383 } 5384 5385 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 5386 N1.getOpcode() == ISD::XOR) 5387 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 5388 return V; 5389 5390 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 5391 return V; 5392 } 5393 5394 // Fold remainder of division by a constant. 5395 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 5396 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 5397 // When division is cheap or optimizing for minimum size, 5398 // fall through to DIVREM creation by skipping this fold. 5399 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 5400 if (N0.getOpcode() == ISD::UREM) { 5401 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5402 return Folded; 5403 } else if (N0.getOpcode() == ISD::SREM) { 5404 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5405 return Folded; 5406 } 5407 } 5408 } 5409 5410 // Fold away ALL boolean setcc's. 5411 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 5412 SDValue Temp; 5413 switch (Cond) { 5414 default: llvm_unreachable("Unknown integer setcc!"); 5415 case ISD::SETEQ: // X == Y -> ~(X^Y) 5416 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5417 N0 = DAG.getNOT(dl, Temp, OpVT); 5418 if (!DCI.isCalledByLegalizer()) 5419 DCI.AddToWorklist(Temp.getNode()); 5420 break; 5421 case ISD::SETNE: // X != Y --> (X^Y) 5422 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5423 break; 5424 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 5425 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 5426 Temp = DAG.getNOT(dl, N0, OpVT); 5427 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 5428 if (!DCI.isCalledByLegalizer()) 5429 DCI.AddToWorklist(Temp.getNode()); 5430 break; 5431 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 5432 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 5433 Temp = DAG.getNOT(dl, N1, OpVT); 5434 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 5435 if (!DCI.isCalledByLegalizer()) 5436 DCI.AddToWorklist(Temp.getNode()); 5437 break; 5438 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 5439 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 5440 Temp = DAG.getNOT(dl, N0, OpVT); 5441 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 5442 if (!DCI.isCalledByLegalizer()) 5443 DCI.AddToWorklist(Temp.getNode()); 5444 break; 5445 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 5446 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 5447 Temp = DAG.getNOT(dl, N1, OpVT); 5448 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 5449 break; 5450 } 5451 if (VT.getScalarType() != MVT::i1) { 5452 if (!DCI.isCalledByLegalizer()) 5453 DCI.AddToWorklist(N0.getNode()); 5454 // FIXME: If running after legalize, we probably can't do this. 5455 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 5456 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 5457 } 5458 return N0; 5459 } 5460 5461 // Could not fold it. 5462 return SDValue(); 5463 } 5464 5465 /// Returns true (and the GlobalValue and the offset) if the node is a 5466 /// GlobalAddress + offset. 5467 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 5468 int64_t &Offset) const { 5469 5470 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 5471 5472 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 5473 GA = GASD->getGlobal(); 5474 Offset += GASD->getOffset(); 5475 return true; 5476 } 5477 5478 if (N->getOpcode() == ISD::ADD) { 5479 SDValue N1 = N->getOperand(0); 5480 SDValue N2 = N->getOperand(1); 5481 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 5482 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 5483 Offset += V->getSExtValue(); 5484 return true; 5485 } 5486 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 5487 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 5488 Offset += V->getSExtValue(); 5489 return true; 5490 } 5491 } 5492 } 5493 5494 return false; 5495 } 5496 5497 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5498 DAGCombinerInfo &DCI) const { 5499 // Default implementation: no optimization. 5500 return SDValue(); 5501 } 5502 5503 //===----------------------------------------------------------------------===// 5504 // Inline Assembler Implementation Methods 5505 //===----------------------------------------------------------------------===// 5506 5507 TargetLowering::ConstraintType 5508 TargetLowering::getConstraintType(StringRef Constraint) const { 5509 unsigned S = Constraint.size(); 5510 5511 if (S == 1) { 5512 switch (Constraint[0]) { 5513 default: break; 5514 case 'r': 5515 return C_RegisterClass; 5516 case 'm': // memory 5517 case 'o': // offsetable 5518 case 'V': // not offsetable 5519 return C_Memory; 5520 case 'p': // Address. 5521 return C_Address; 5522 case 'n': // Simple Integer 5523 case 'E': // Floating Point Constant 5524 case 'F': // Floating Point Constant 5525 return C_Immediate; 5526 case 'i': // Simple Integer or Relocatable Constant 5527 case 's': // Relocatable Constant 5528 case 'X': // Allow ANY value. 5529 case 'I': // Target registers. 5530 case 'J': 5531 case 'K': 5532 case 'L': 5533 case 'M': 5534 case 'N': 5535 case 'O': 5536 case 'P': 5537 case '<': 5538 case '>': 5539 return C_Other; 5540 } 5541 } 5542 5543 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5544 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5545 return C_Memory; 5546 return C_Register; 5547 } 5548 return C_Unknown; 5549 } 5550 5551 /// Try to replace an X constraint, which matches anything, with another that 5552 /// has more specific requirements based on the type of the corresponding 5553 /// operand. 5554 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5555 if (ConstraintVT.isInteger()) 5556 return "r"; 5557 if (ConstraintVT.isFloatingPoint()) 5558 return "f"; // works for many targets 5559 return nullptr; 5560 } 5561 5562 SDValue TargetLowering::LowerAsmOutputForConstraint( 5563 SDValue &Chain, SDValue &Glue, const SDLoc &DL, 5564 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5565 return SDValue(); 5566 } 5567 5568 /// Lower the specified operand into the Ops vector. 5569 /// If it is invalid, don't add anything to Ops. 5570 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5571 StringRef Constraint, 5572 std::vector<SDValue> &Ops, 5573 SelectionDAG &DAG) const { 5574 5575 if (Constraint.size() > 1) 5576 return; 5577 5578 char ConstraintLetter = Constraint[0]; 5579 switch (ConstraintLetter) { 5580 default: break; 5581 case 'X': // Allows any operand 5582 case 'i': // Simple Integer or Relocatable Constant 5583 case 'n': // Simple Integer 5584 case 's': { // Relocatable Constant 5585 5586 ConstantSDNode *C; 5587 uint64_t Offset = 0; 5588 5589 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5590 // etc., since getelementpointer is variadic. We can't use 5591 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5592 // while in this case the GA may be furthest from the root node which is 5593 // likely an ISD::ADD. 5594 while (true) { 5595 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5596 // gcc prints these as sign extended. Sign extend value to 64 bits 5597 // now; without this it would get ZExt'd later in 5598 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5599 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5600 BooleanContent BCont = getBooleanContents(MVT::i64); 5601 ISD::NodeType ExtOpc = 5602 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5603 int64_t ExtVal = 5604 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5605 Ops.push_back( 5606 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5607 return; 5608 } 5609 if (ConstraintLetter != 'n') { 5610 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5611 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5612 GA->getValueType(0), 5613 Offset + GA->getOffset())); 5614 return; 5615 } 5616 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5617 Ops.push_back(DAG.getTargetBlockAddress( 5618 BA->getBlockAddress(), BA->getValueType(0), 5619 Offset + BA->getOffset(), BA->getTargetFlags())); 5620 return; 5621 } 5622 if (isa<BasicBlockSDNode>(Op)) { 5623 Ops.push_back(Op); 5624 return; 5625 } 5626 } 5627 const unsigned OpCode = Op.getOpcode(); 5628 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5629 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5630 Op = Op.getOperand(1); 5631 // Subtraction is not commutative. 5632 else if (OpCode == ISD::ADD && 5633 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5634 Op = Op.getOperand(0); 5635 else 5636 return; 5637 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5638 continue; 5639 } 5640 return; 5641 } 5642 break; 5643 } 5644 } 5645 } 5646 5647 void TargetLowering::CollectTargetIntrinsicOperands( 5648 const CallInst &I, SmallVectorImpl<SDValue> &Ops, SelectionDAG &DAG) const { 5649 } 5650 5651 std::pair<unsigned, const TargetRegisterClass *> 5652 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5653 StringRef Constraint, 5654 MVT VT) const { 5655 if (!Constraint.starts_with("{")) 5656 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5657 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5658 5659 // Remove the braces from around the name. 5660 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5661 5662 std::pair<unsigned, const TargetRegisterClass *> R = 5663 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5664 5665 // Figure out which register class contains this reg. 5666 for (const TargetRegisterClass *RC : RI->regclasses()) { 5667 // If none of the value types for this register class are valid, we 5668 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5669 if (!isLegalRC(*RI, *RC)) 5670 continue; 5671 5672 for (const MCPhysReg &PR : *RC) { 5673 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5674 std::pair<unsigned, const TargetRegisterClass *> S = 5675 std::make_pair(PR, RC); 5676 5677 // If this register class has the requested value type, return it, 5678 // otherwise keep searching and return the first class found 5679 // if no other is found which explicitly has the requested type. 5680 if (RI->isTypeLegalForClass(*RC, VT)) 5681 return S; 5682 if (!R.second) 5683 R = S; 5684 } 5685 } 5686 } 5687 5688 return R; 5689 } 5690 5691 //===----------------------------------------------------------------------===// 5692 // Constraint Selection. 5693 5694 /// Return true of this is an input operand that is a matching constraint like 5695 /// "4". 5696 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5697 assert(!ConstraintCode.empty() && "No known constraint!"); 5698 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5699 } 5700 5701 /// If this is an input matching constraint, this method returns the output 5702 /// operand it matches. 5703 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5704 assert(!ConstraintCode.empty() && "No known constraint!"); 5705 return atoi(ConstraintCode.c_str()); 5706 } 5707 5708 /// Split up the constraint string from the inline assembly value into the 5709 /// specific constraints and their prefixes, and also tie in the associated 5710 /// operand values. 5711 /// If this returns an empty vector, and if the constraint string itself 5712 /// isn't empty, there was an error parsing. 5713 TargetLowering::AsmOperandInfoVector 5714 TargetLowering::ParseConstraints(const DataLayout &DL, 5715 const TargetRegisterInfo *TRI, 5716 const CallBase &Call) const { 5717 /// Information about all of the constraints. 5718 AsmOperandInfoVector ConstraintOperands; 5719 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5720 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5721 5722 // Do a prepass over the constraints, canonicalizing them, and building up the 5723 // ConstraintOperands list. 5724 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5725 unsigned ResNo = 0; // ResNo - The result number of the next output. 5726 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number. 5727 5728 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5729 ConstraintOperands.emplace_back(std::move(CI)); 5730 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5731 5732 // Update multiple alternative constraint count. 5733 if (OpInfo.multipleAlternatives.size() > maCount) 5734 maCount = OpInfo.multipleAlternatives.size(); 5735 5736 OpInfo.ConstraintVT = MVT::Other; 5737 5738 // Compute the value type for each operand. 5739 switch (OpInfo.Type) { 5740 case InlineAsm::isOutput: 5741 // Indirect outputs just consume an argument. 5742 if (OpInfo.isIndirect) { 5743 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5744 break; 5745 } 5746 5747 // The return value of the call is this value. As such, there is no 5748 // corresponding argument. 5749 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5750 if (auto *STy = dyn_cast<StructType>(Call.getType())) { 5751 OpInfo.ConstraintVT = 5752 getSimpleValueType(DL, STy->getElementType(ResNo)); 5753 } else { 5754 assert(ResNo == 0 && "Asm only has one result!"); 5755 OpInfo.ConstraintVT = 5756 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5757 } 5758 ++ResNo; 5759 break; 5760 case InlineAsm::isInput: 5761 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5762 break; 5763 case InlineAsm::isLabel: 5764 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo); 5765 ++LabelNo; 5766 continue; 5767 case InlineAsm::isClobber: 5768 // Nothing to do. 5769 break; 5770 } 5771 5772 if (OpInfo.CallOperandVal) { 5773 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5774 if (OpInfo.isIndirect) { 5775 OpTy = Call.getParamElementType(ArgNo); 5776 assert(OpTy && "Indirect operand must have elementtype attribute"); 5777 } 5778 5779 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5780 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5781 if (STy->getNumElements() == 1) 5782 OpTy = STy->getElementType(0); 5783 5784 // If OpTy is not a single value, it may be a struct/union that we 5785 // can tile with integers. 5786 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5787 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5788 switch (BitSize) { 5789 default: break; 5790 case 1: 5791 case 8: 5792 case 16: 5793 case 32: 5794 case 64: 5795 case 128: 5796 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5797 break; 5798 } 5799 } 5800 5801 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5802 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5803 ArgNo++; 5804 } 5805 } 5806 5807 // If we have multiple alternative constraints, select the best alternative. 5808 if (!ConstraintOperands.empty()) { 5809 if (maCount) { 5810 unsigned bestMAIndex = 0; 5811 int bestWeight = -1; 5812 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5813 int weight = -1; 5814 unsigned maIndex; 5815 // Compute the sums of the weights for each alternative, keeping track 5816 // of the best (highest weight) one so far. 5817 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5818 int weightSum = 0; 5819 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5820 cIndex != eIndex; ++cIndex) { 5821 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5822 if (OpInfo.Type == InlineAsm::isClobber) 5823 continue; 5824 5825 // If this is an output operand with a matching input operand, 5826 // look up the matching input. If their types mismatch, e.g. one 5827 // is an integer, the other is floating point, or their sizes are 5828 // different, flag it as an maCantMatch. 5829 if (OpInfo.hasMatchingInput()) { 5830 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5831 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5832 if ((OpInfo.ConstraintVT.isInteger() != 5833 Input.ConstraintVT.isInteger()) || 5834 (OpInfo.ConstraintVT.getSizeInBits() != 5835 Input.ConstraintVT.getSizeInBits())) { 5836 weightSum = -1; // Can't match. 5837 break; 5838 } 5839 } 5840 } 5841 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5842 if (weight == -1) { 5843 weightSum = -1; 5844 break; 5845 } 5846 weightSum += weight; 5847 } 5848 // Update best. 5849 if (weightSum > bestWeight) { 5850 bestWeight = weightSum; 5851 bestMAIndex = maIndex; 5852 } 5853 } 5854 5855 // Now select chosen alternative in each constraint. 5856 for (AsmOperandInfo &cInfo : ConstraintOperands) 5857 if (cInfo.Type != InlineAsm::isClobber) 5858 cInfo.selectAlternative(bestMAIndex); 5859 } 5860 } 5861 5862 // Check and hook up tied operands, choose constraint code to use. 5863 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5864 cIndex != eIndex; ++cIndex) { 5865 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5866 5867 // If this is an output operand with a matching input operand, look up the 5868 // matching input. If their types mismatch, e.g. one is an integer, the 5869 // other is floating point, or their sizes are different, flag it as an 5870 // error. 5871 if (OpInfo.hasMatchingInput()) { 5872 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5873 5874 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5875 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5876 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5877 OpInfo.ConstraintVT); 5878 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5879 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5880 Input.ConstraintVT); 5881 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() || 5882 OpInfo.ConstraintVT.isFloatingPoint(); 5883 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() || 5884 Input.ConstraintVT.isFloatingPoint(); 5885 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || 5886 (MatchRC.second != InputRC.second)) { 5887 report_fatal_error("Unsupported asm: input constraint" 5888 " with a matching output constraint of" 5889 " incompatible type!"); 5890 } 5891 } 5892 } 5893 } 5894 5895 return ConstraintOperands; 5896 } 5897 5898 /// Return a number indicating our preference for chosing a type of constraint 5899 /// over another, for the purpose of sorting them. Immediates are almost always 5900 /// preferrable (when they can be emitted). A higher return value means a 5901 /// stronger preference for one constraint type relative to another. 5902 /// FIXME: We should prefer registers over memory but doing so may lead to 5903 /// unrecoverable register exhaustion later. 5904 /// https://github.com/llvm/llvm-project/issues/20571 5905 static unsigned getConstraintPiority(TargetLowering::ConstraintType CT) { 5906 switch (CT) { 5907 case TargetLowering::C_Immediate: 5908 case TargetLowering::C_Other: 5909 return 4; 5910 case TargetLowering::C_Memory: 5911 case TargetLowering::C_Address: 5912 return 3; 5913 case TargetLowering::C_RegisterClass: 5914 return 2; 5915 case TargetLowering::C_Register: 5916 return 1; 5917 case TargetLowering::C_Unknown: 5918 return 0; 5919 } 5920 llvm_unreachable("Invalid constraint type"); 5921 } 5922 5923 /// Examine constraint type and operand type and determine a weight value. 5924 /// This object must already have been set up with the operand type 5925 /// and the current alternative constraint selected. 5926 TargetLowering::ConstraintWeight 5927 TargetLowering::getMultipleConstraintMatchWeight( 5928 AsmOperandInfo &info, int maIndex) const { 5929 InlineAsm::ConstraintCodeVector *rCodes; 5930 if (maIndex >= (int)info.multipleAlternatives.size()) 5931 rCodes = &info.Codes; 5932 else 5933 rCodes = &info.multipleAlternatives[maIndex].Codes; 5934 ConstraintWeight BestWeight = CW_Invalid; 5935 5936 // Loop over the options, keeping track of the most general one. 5937 for (const std::string &rCode : *rCodes) { 5938 ConstraintWeight weight = 5939 getSingleConstraintMatchWeight(info, rCode.c_str()); 5940 if (weight > BestWeight) 5941 BestWeight = weight; 5942 } 5943 5944 return BestWeight; 5945 } 5946 5947 /// Examine constraint type and operand type and determine a weight value. 5948 /// This object must already have been set up with the operand type 5949 /// and the current alternative constraint selected. 5950 TargetLowering::ConstraintWeight 5951 TargetLowering::getSingleConstraintMatchWeight( 5952 AsmOperandInfo &info, const char *constraint) const { 5953 ConstraintWeight weight = CW_Invalid; 5954 Value *CallOperandVal = info.CallOperandVal; 5955 // If we don't have a value, we can't do a match, 5956 // but allow it at the lowest weight. 5957 if (!CallOperandVal) 5958 return CW_Default; 5959 // Look at the constraint type. 5960 switch (*constraint) { 5961 case 'i': // immediate integer. 5962 case 'n': // immediate integer with a known value. 5963 if (isa<ConstantInt>(CallOperandVal)) 5964 weight = CW_Constant; 5965 break; 5966 case 's': // non-explicit intregal immediate. 5967 if (isa<GlobalValue>(CallOperandVal)) 5968 weight = CW_Constant; 5969 break; 5970 case 'E': // immediate float if host format. 5971 case 'F': // immediate float. 5972 if (isa<ConstantFP>(CallOperandVal)) 5973 weight = CW_Constant; 5974 break; 5975 case '<': // memory operand with autodecrement. 5976 case '>': // memory operand with autoincrement. 5977 case 'm': // memory operand. 5978 case 'o': // offsettable memory operand 5979 case 'V': // non-offsettable memory operand 5980 weight = CW_Memory; 5981 break; 5982 case 'r': // general register. 5983 case 'g': // general register, memory operand or immediate integer. 5984 // note: Clang converts "g" to "imr". 5985 if (CallOperandVal->getType()->isIntegerTy()) 5986 weight = CW_Register; 5987 break; 5988 case 'X': // any operand. 5989 default: 5990 weight = CW_Default; 5991 break; 5992 } 5993 return weight; 5994 } 5995 5996 /// If there are multiple different constraints that we could pick for this 5997 /// operand (e.g. "imr") try to pick the 'best' one. 5998 /// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall 5999 /// into seven classes: 6000 /// Register -> one specific register 6001 /// RegisterClass -> a group of regs 6002 /// Memory -> memory 6003 /// Address -> a symbolic memory reference 6004 /// Immediate -> immediate values 6005 /// Other -> magic values (such as "Flag Output Operands") 6006 /// Unknown -> something we don't recognize yet and can't handle 6007 /// Ideally, we would pick the most specific constraint possible: if we have 6008 /// something that fits into a register, we would pick it. The problem here 6009 /// is that if we have something that could either be in a register or in 6010 /// memory that use of the register could cause selection of *other* 6011 /// operands to fail: they might only succeed if we pick memory. Because of 6012 /// this the heuristic we use is: 6013 /// 6014 /// 1) If there is an 'other' constraint, and if the operand is valid for 6015 /// that constraint, use it. This makes us take advantage of 'i' 6016 /// constraints when available. 6017 /// 2) Otherwise, pick the most general constraint present. This prefers 6018 /// 'm' over 'r', for example. 6019 /// 6020 TargetLowering::ConstraintGroup TargetLowering::getConstraintPreferences( 6021 TargetLowering::AsmOperandInfo &OpInfo) const { 6022 ConstraintGroup Ret; 6023 6024 Ret.reserve(OpInfo.Codes.size()); 6025 for (StringRef Code : OpInfo.Codes) { 6026 TargetLowering::ConstraintType CType = getConstraintType(Code); 6027 6028 // Indirect 'other' or 'immediate' constraints are not allowed. 6029 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 6030 CType == TargetLowering::C_Register || 6031 CType == TargetLowering::C_RegisterClass)) 6032 continue; 6033 6034 // Things with matching constraints can only be registers, per gcc 6035 // documentation. This mainly affects "g" constraints. 6036 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 6037 continue; 6038 6039 Ret.emplace_back(Code, CType); 6040 } 6041 6042 std::stable_sort( 6043 Ret.begin(), Ret.end(), [](ConstraintPair a, ConstraintPair b) { 6044 return getConstraintPiority(a.second) > getConstraintPiority(b.second); 6045 }); 6046 6047 return Ret; 6048 } 6049 6050 /// If we have an immediate, see if we can lower it. Return true if we can, 6051 /// false otherwise. 6052 static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, 6053 SDValue Op, SelectionDAG *DAG, 6054 const TargetLowering &TLI) { 6055 6056 assert((P.second == TargetLowering::C_Other || 6057 P.second == TargetLowering::C_Immediate) && 6058 "need immediate or other"); 6059 6060 if (!Op.getNode()) 6061 return false; 6062 6063 std::vector<SDValue> ResultOps; 6064 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG); 6065 return !ResultOps.empty(); 6066 } 6067 6068 /// Determines the constraint code and constraint type to use for the specific 6069 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 6070 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 6071 SDValue Op, 6072 SelectionDAG *DAG) const { 6073 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 6074 6075 // Single-letter constraints ('r') are very common. 6076 if (OpInfo.Codes.size() == 1) { 6077 OpInfo.ConstraintCode = OpInfo.Codes[0]; 6078 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 6079 } else { 6080 ConstraintGroup G = getConstraintPreferences(OpInfo); 6081 if (G.empty()) 6082 return; 6083 6084 unsigned BestIdx = 0; 6085 for (const unsigned E = G.size(); 6086 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other || 6087 G[BestIdx].second == TargetLowering::C_Immediate); 6088 ++BestIdx) { 6089 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this)) 6090 break; 6091 // If we're out of constraints, just pick the first one. 6092 if (BestIdx + 1 == E) { 6093 BestIdx = 0; 6094 break; 6095 } 6096 } 6097 6098 OpInfo.ConstraintCode = G[BestIdx].first; 6099 OpInfo.ConstraintType = G[BestIdx].second; 6100 } 6101 6102 // 'X' matches anything. 6103 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 6104 // Constants are handled elsewhere. For Functions, the type here is the 6105 // type of the result, which is not what we want to look at; leave them 6106 // alone. 6107 Value *v = OpInfo.CallOperandVal; 6108 if (isa<ConstantInt>(v) || isa<Function>(v)) { 6109 return; 6110 } 6111 6112 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 6113 OpInfo.ConstraintCode = "i"; 6114 return; 6115 } 6116 6117 // Otherwise, try to resolve it to something we know about by looking at 6118 // the actual operand type. 6119 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 6120 OpInfo.ConstraintCode = Repl; 6121 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 6122 } 6123 } 6124 } 6125 6126 /// Given an exact SDIV by a constant, create a multiplication 6127 /// with the multiplicative inverse of the constant. 6128 /// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242 6129 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 6130 const SDLoc &dl, SelectionDAG &DAG, 6131 SmallVectorImpl<SDNode *> &Created) { 6132 SDValue Op0 = N->getOperand(0); 6133 SDValue Op1 = N->getOperand(1); 6134 EVT VT = N->getValueType(0); 6135 EVT SVT = VT.getScalarType(); 6136 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 6137 EVT ShSVT = ShVT.getScalarType(); 6138 6139 bool UseSRA = false; 6140 SmallVector<SDValue, 16> Shifts, Factors; 6141 6142 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6143 if (C->isZero()) 6144 return false; 6145 APInt Divisor = C->getAPIntValue(); 6146 unsigned Shift = Divisor.countr_zero(); 6147 if (Shift) { 6148 Divisor.ashrInPlace(Shift); 6149 UseSRA = true; 6150 } 6151 APInt Factor = Divisor.multiplicativeInverse(); 6152 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 6153 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 6154 return true; 6155 }; 6156 6157 // Collect all magic values from the build vector. 6158 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 6159 return SDValue(); 6160 6161 SDValue Shift, Factor; 6162 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 6163 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6164 Factor = DAG.getBuildVector(VT, dl, Factors); 6165 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 6166 assert(Shifts.size() == 1 && Factors.size() == 1 && 6167 "Expected matchUnaryPredicate to return one element for scalable " 6168 "vectors"); 6169 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6170 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6171 } else { 6172 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 6173 Shift = Shifts[0]; 6174 Factor = Factors[0]; 6175 } 6176 6177 SDValue Res = Op0; 6178 if (UseSRA) { 6179 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact); 6180 Created.push_back(Res.getNode()); 6181 } 6182 6183 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 6184 } 6185 6186 /// Given an exact UDIV by a constant, create a multiplication 6187 /// with the multiplicative inverse of the constant. 6188 /// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242 6189 static SDValue BuildExactUDIV(const TargetLowering &TLI, SDNode *N, 6190 const SDLoc &dl, SelectionDAG &DAG, 6191 SmallVectorImpl<SDNode *> &Created) { 6192 EVT VT = N->getValueType(0); 6193 EVT SVT = VT.getScalarType(); 6194 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 6195 EVT ShSVT = ShVT.getScalarType(); 6196 6197 bool UseSRL = false; 6198 SmallVector<SDValue, 16> Shifts, Factors; 6199 6200 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 6201 if (C->isZero()) 6202 return false; 6203 APInt Divisor = C->getAPIntValue(); 6204 unsigned Shift = Divisor.countr_zero(); 6205 if (Shift) { 6206 Divisor.lshrInPlace(Shift); 6207 UseSRL = true; 6208 } 6209 // Calculate the multiplicative inverse modulo BW. 6210 APInt Factor = Divisor.multiplicativeInverse(); 6211 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 6212 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 6213 return true; 6214 }; 6215 6216 SDValue Op1 = N->getOperand(1); 6217 6218 // Collect all magic values from the build vector. 6219 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern)) 6220 return SDValue(); 6221 6222 SDValue Shift, Factor; 6223 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 6224 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6225 Factor = DAG.getBuildVector(VT, dl, Factors); 6226 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 6227 assert(Shifts.size() == 1 && Factors.size() == 1 && 6228 "Expected matchUnaryPredicate to return one element for scalable " 6229 "vectors"); 6230 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6231 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6232 } else { 6233 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 6234 Shift = Shifts[0]; 6235 Factor = Factors[0]; 6236 } 6237 6238 SDValue Res = N->getOperand(0); 6239 if (UseSRL) { 6240 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact); 6241 Created.push_back(Res.getNode()); 6242 } 6243 6244 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 6245 } 6246 6247 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 6248 SelectionDAG &DAG, 6249 SmallVectorImpl<SDNode *> &Created) const { 6250 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6251 if (isIntDivCheap(N->getValueType(0), Attr)) 6252 return SDValue(N, 0); // Lower SDIV as SDIV 6253 return SDValue(); 6254 } 6255 6256 SDValue 6257 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 6258 SelectionDAG &DAG, 6259 SmallVectorImpl<SDNode *> &Created) const { 6260 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6261 if (isIntDivCheap(N->getValueType(0), Attr)) 6262 return SDValue(N, 0); // Lower SREM as SREM 6263 return SDValue(); 6264 } 6265 6266 /// Build sdiv by power-of-2 with conditional move instructions 6267 /// Ref: "Hacker's Delight" by Henry Warren 10-1 6268 /// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into: 6269 /// bgez x, label 6270 /// add x, x, 2**k-1 6271 /// label: 6272 /// sra res, x, k 6273 /// neg res, res (when the divisor is negative) 6274 SDValue TargetLowering::buildSDIVPow2WithCMov( 6275 SDNode *N, const APInt &Divisor, SelectionDAG &DAG, 6276 SmallVectorImpl<SDNode *> &Created) const { 6277 unsigned Lg2 = Divisor.countr_zero(); 6278 EVT VT = N->getValueType(0); 6279 6280 SDLoc DL(N); 6281 SDValue N0 = N->getOperand(0); 6282 SDValue Zero = DAG.getConstant(0, DL, VT); 6283 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2); 6284 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT); 6285 6286 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right. 6287 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6288 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT); 6289 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 6290 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 6291 6292 Created.push_back(Cmp.getNode()); 6293 Created.push_back(Add.getNode()); 6294 Created.push_back(CMov.getNode()); 6295 6296 // Divide by pow2. 6297 SDValue SRA = 6298 DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, VT)); 6299 6300 // If we're dividing by a positive value, we're done. Otherwise, we must 6301 // negate the result. 6302 if (Divisor.isNonNegative()) 6303 return SRA; 6304 6305 Created.push_back(SRA.getNode()); 6306 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA); 6307 } 6308 6309 /// Given an ISD::SDIV node expressing a divide by constant, 6310 /// return a DAG expression to select that will generate the same value by 6311 /// multiplying by a magic number. 6312 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6313 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 6314 bool IsAfterLegalization, 6315 bool IsAfterLegalTypes, 6316 SmallVectorImpl<SDNode *> &Created) const { 6317 SDLoc dl(N); 6318 EVT VT = N->getValueType(0); 6319 EVT SVT = VT.getScalarType(); 6320 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6321 EVT ShSVT = ShVT.getScalarType(); 6322 unsigned EltBits = VT.getScalarSizeInBits(); 6323 EVT MulVT; 6324 6325 // Check to see if we can do this. 6326 // FIXME: We should be more aggressive here. 6327 if (!isTypeLegal(VT)) { 6328 // Limit this to simple scalars for now. 6329 if (VT.isVector() || !VT.isSimple()) 6330 return SDValue(); 6331 6332 // If this type will be promoted to a large enough type with a legal 6333 // multiply operation, we can go ahead and do this transform. 6334 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6335 return SDValue(); 6336 6337 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6338 if (MulVT.getSizeInBits() < (2 * EltBits) || 6339 !isOperationLegal(ISD::MUL, MulVT)) 6340 return SDValue(); 6341 } 6342 6343 // If the sdiv has an 'exact' bit we can use a simpler lowering. 6344 if (N->getFlags().hasExact()) 6345 return BuildExactSDIV(*this, N, dl, DAG, Created); 6346 6347 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 6348 6349 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6350 if (C->isZero()) 6351 return false; 6352 6353 const APInt &Divisor = C->getAPIntValue(); 6354 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 6355 int NumeratorFactor = 0; 6356 int ShiftMask = -1; 6357 6358 if (Divisor.isOne() || Divisor.isAllOnes()) { 6359 // If d is +1/-1, we just multiply the numerator by +1/-1. 6360 NumeratorFactor = Divisor.getSExtValue(); 6361 magics.Magic = 0; 6362 magics.ShiftAmount = 0; 6363 ShiftMask = 0; 6364 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 6365 // If d > 0 and m < 0, add the numerator. 6366 NumeratorFactor = 1; 6367 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 6368 // If d < 0 and m > 0, subtract the numerator. 6369 NumeratorFactor = -1; 6370 } 6371 6372 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 6373 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT)); 6374 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 6375 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT)); 6376 return true; 6377 }; 6378 6379 SDValue N0 = N->getOperand(0); 6380 SDValue N1 = N->getOperand(1); 6381 6382 // Collect the shifts / magic values from each element. 6383 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 6384 return SDValue(); 6385 6386 SDValue MagicFactor, Factor, Shift, ShiftMask; 6387 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6388 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6389 Factor = DAG.getBuildVector(VT, dl, Factors); 6390 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6391 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 6392 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6393 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 6394 Shifts.size() == 1 && ShiftMasks.size() == 1 && 6395 "Expected matchUnaryPredicate to return one element for scalable " 6396 "vectors"); 6397 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6398 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6399 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6400 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 6401 } else { 6402 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6403 MagicFactor = MagicFactors[0]; 6404 Factor = Factors[0]; 6405 Shift = Shifts[0]; 6406 ShiftMask = ShiftMasks[0]; 6407 } 6408 6409 // Multiply the numerator (operand 0) by the magic value. 6410 // FIXME: We should support doing a MUL in a wider type. 6411 auto GetMULHS = [&](SDValue X, SDValue Y) { 6412 // If the type isn't legal, use a wider mul of the type calculated 6413 // earlier. 6414 if (!isTypeLegal(VT)) { 6415 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 6416 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 6417 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6418 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6419 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6420 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6421 } 6422 6423 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 6424 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 6425 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 6426 SDValue LoHi = 6427 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6428 return SDValue(LoHi.getNode(), 1); 6429 } 6430 // If type twice as wide legal, widen and use a mul plus a shift. 6431 unsigned Size = VT.getScalarSizeInBits(); 6432 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6433 if (VT.isVector()) 6434 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6435 VT.getVectorElementCount()); 6436 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then 6437 // custom lowered. This is very expensive so avoid it at all costs for 6438 // constant divisors. 6439 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) && 6440 isOperationCustom(ISD::SDIVREM, VT.getScalarType())) || 6441 isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6442 X = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, X); 6443 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, Y); 6444 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6445 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6446 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6447 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6448 } 6449 return SDValue(); 6450 }; 6451 6452 SDValue Q = GetMULHS(N0, MagicFactor); 6453 if (!Q) 6454 return SDValue(); 6455 6456 Created.push_back(Q.getNode()); 6457 6458 // (Optionally) Add/subtract the numerator using Factor. 6459 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 6460 Created.push_back(Factor.getNode()); 6461 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 6462 Created.push_back(Q.getNode()); 6463 6464 // Shift right algebraic by shift value. 6465 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 6466 Created.push_back(Q.getNode()); 6467 6468 // Extract the sign bit, mask it and add it to the quotient. 6469 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 6470 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 6471 Created.push_back(T.getNode()); 6472 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 6473 Created.push_back(T.getNode()); 6474 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 6475 } 6476 6477 /// Given an ISD::UDIV node expressing a divide by constant, 6478 /// return a DAG expression to select that will generate the same value by 6479 /// multiplying by a magic number. 6480 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6481 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 6482 bool IsAfterLegalization, 6483 bool IsAfterLegalTypes, 6484 SmallVectorImpl<SDNode *> &Created) const { 6485 SDLoc dl(N); 6486 EVT VT = N->getValueType(0); 6487 EVT SVT = VT.getScalarType(); 6488 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6489 EVT ShSVT = ShVT.getScalarType(); 6490 unsigned EltBits = VT.getScalarSizeInBits(); 6491 EVT MulVT; 6492 6493 // Check to see if we can do this. 6494 // FIXME: We should be more aggressive here. 6495 if (!isTypeLegal(VT)) { 6496 // Limit this to simple scalars for now. 6497 if (VT.isVector() || !VT.isSimple()) 6498 return SDValue(); 6499 6500 // If this type will be promoted to a large enough type with a legal 6501 // multiply operation, we can go ahead and do this transform. 6502 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6503 return SDValue(); 6504 6505 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6506 if (MulVT.getSizeInBits() < (2 * EltBits) || 6507 !isOperationLegal(ISD::MUL, MulVT)) 6508 return SDValue(); 6509 } 6510 6511 // If the udiv has an 'exact' bit we can use a simpler lowering. 6512 if (N->getFlags().hasExact()) 6513 return BuildExactUDIV(*this, N, dl, DAG, Created); 6514 6515 SDValue N0 = N->getOperand(0); 6516 SDValue N1 = N->getOperand(1); 6517 6518 // Try to use leading zeros of the dividend to reduce the multiplier and 6519 // avoid expensive fixups. 6520 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros(); 6521 6522 bool UseNPQ = false, UsePreShift = false, UsePostShift = false; 6523 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 6524 6525 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 6526 if (C->isZero()) 6527 return false; 6528 const APInt& Divisor = C->getAPIntValue(); 6529 6530 SDValue PreShift, MagicFactor, NPQFactor, PostShift; 6531 6532 // Magic algorithm doesn't work for division by 1. We need to emit a select 6533 // at the end. 6534 if (Divisor.isOne()) { 6535 PreShift = PostShift = DAG.getUNDEF(ShSVT); 6536 MagicFactor = NPQFactor = DAG.getUNDEF(SVT); 6537 } else { 6538 UnsignedDivisionByConstantInfo magics = 6539 UnsignedDivisionByConstantInfo::get( 6540 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero())); 6541 6542 MagicFactor = DAG.getConstant(magics.Magic, dl, SVT); 6543 6544 assert(magics.PreShift < Divisor.getBitWidth() && 6545 "We shouldn't generate an undefined shift!"); 6546 assert(magics.PostShift < Divisor.getBitWidth() && 6547 "We shouldn't generate an undefined shift!"); 6548 assert((!magics.IsAdd || magics.PreShift == 0) && 6549 "Unexpected pre-shift"); 6550 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT); 6551 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT); 6552 NPQFactor = DAG.getConstant( 6553 magics.IsAdd ? APInt::getOneBitSet(EltBits, EltBits - 1) 6554 : APInt::getZero(EltBits), 6555 dl, SVT); 6556 UseNPQ |= magics.IsAdd; 6557 UsePreShift |= magics.PreShift != 0; 6558 UsePostShift |= magics.PostShift != 0; 6559 } 6560 6561 PreShifts.push_back(PreShift); 6562 MagicFactors.push_back(MagicFactor); 6563 NPQFactors.push_back(NPQFactor); 6564 PostShifts.push_back(PostShift); 6565 return true; 6566 }; 6567 6568 // Collect the shifts/magic values from each element. 6569 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 6570 return SDValue(); 6571 6572 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 6573 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6574 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 6575 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6576 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 6577 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 6578 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6579 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 6580 NPQFactors.size() == 1 && PostShifts.size() == 1 && 6581 "Expected matchUnaryPredicate to return one for scalable vectors"); 6582 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 6583 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6584 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 6585 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 6586 } else { 6587 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6588 PreShift = PreShifts[0]; 6589 MagicFactor = MagicFactors[0]; 6590 PostShift = PostShifts[0]; 6591 } 6592 6593 SDValue Q = N0; 6594 if (UsePreShift) { 6595 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 6596 Created.push_back(Q.getNode()); 6597 } 6598 6599 // FIXME: We should support doing a MUL in a wider type. 6600 auto GetMULHU = [&](SDValue X, SDValue Y) { 6601 // If the type isn't legal, use a wider mul of the type calculated 6602 // earlier. 6603 if (!isTypeLegal(VT)) { 6604 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 6605 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 6606 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6607 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6608 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6609 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6610 } 6611 6612 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 6613 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 6614 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 6615 SDValue LoHi = 6616 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6617 return SDValue(LoHi.getNode(), 1); 6618 } 6619 // If type twice as wide legal, widen and use a mul plus a shift. 6620 unsigned Size = VT.getScalarSizeInBits(); 6621 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6622 if (VT.isVector()) 6623 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6624 VT.getVectorElementCount()); 6625 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then 6626 // custom lowered. This is very expensive so avoid it at all costs for 6627 // constant divisors. 6628 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) && 6629 isOperationCustom(ISD::UDIVREM, VT.getScalarType())) || 6630 isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6631 X = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, X); 6632 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, Y); 6633 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6634 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6635 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6636 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6637 } 6638 return SDValue(); // No mulhu or equivalent 6639 }; 6640 6641 // Multiply the numerator (operand 0) by the magic value. 6642 Q = GetMULHU(Q, MagicFactor); 6643 if (!Q) 6644 return SDValue(); 6645 6646 Created.push_back(Q.getNode()); 6647 6648 if (UseNPQ) { 6649 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 6650 Created.push_back(NPQ.getNode()); 6651 6652 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 6653 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 6654 if (VT.isVector()) 6655 NPQ = GetMULHU(NPQ, NPQFactor); 6656 else 6657 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 6658 6659 Created.push_back(NPQ.getNode()); 6660 6661 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 6662 Created.push_back(Q.getNode()); 6663 } 6664 6665 if (UsePostShift) { 6666 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 6667 Created.push_back(Q.getNode()); 6668 } 6669 6670 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6671 6672 SDValue One = DAG.getConstant(1, dl, VT); 6673 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 6674 return DAG.getSelect(dl, VT, IsOne, N0, Q); 6675 } 6676 6677 /// If all values in Values that *don't* match the predicate are same 'splat' 6678 /// value, then replace all values with that splat value. 6679 /// Else, if AlternativeReplacement was provided, then replace all values that 6680 /// do match predicate with AlternativeReplacement value. 6681 static void 6682 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6683 std::function<bool(SDValue)> Predicate, 6684 SDValue AlternativeReplacement = SDValue()) { 6685 SDValue Replacement; 6686 // Is there a value for which the Predicate does *NOT* match? What is it? 6687 auto SplatValue = llvm::find_if_not(Values, Predicate); 6688 if (SplatValue != Values.end()) { 6689 // Does Values consist only of SplatValue's and values matching Predicate? 6690 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6691 return Value == *SplatValue || Predicate(Value); 6692 })) // Then we shall replace values matching predicate with SplatValue. 6693 Replacement = *SplatValue; 6694 } 6695 if (!Replacement) { 6696 // Oops, we did not find the "baseline" splat value. 6697 if (!AlternativeReplacement) 6698 return; // Nothing to do. 6699 // Let's replace with provided value then. 6700 Replacement = AlternativeReplacement; 6701 } 6702 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6703 } 6704 6705 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6706 /// where the divisor is constant and the comparison target is zero, 6707 /// return a DAG expression that will generate the same comparison result 6708 /// using only multiplications, additions and shifts/rotations. 6709 /// Ref: "Hacker's Delight" 10-17. 6710 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6711 SDValue CompTargetNode, 6712 ISD::CondCode Cond, 6713 DAGCombinerInfo &DCI, 6714 const SDLoc &DL) const { 6715 SmallVector<SDNode *, 5> Built; 6716 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6717 DCI, DL, Built)) { 6718 for (SDNode *N : Built) 6719 DCI.AddToWorklist(N); 6720 return Folded; 6721 } 6722 6723 return SDValue(); 6724 } 6725 6726 SDValue 6727 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6728 SDValue CompTargetNode, ISD::CondCode Cond, 6729 DAGCombinerInfo &DCI, const SDLoc &DL, 6730 SmallVectorImpl<SDNode *> &Created) const { 6731 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6732 // - D must be constant, with D = D0 * 2^K where D0 is odd 6733 // - P is the multiplicative inverse of D0 modulo 2^W 6734 // - Q = floor(((2^W) - 1) / D) 6735 // where W is the width of the common type of N and D. 6736 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6737 "Only applicable for (in)equality comparisons."); 6738 6739 SelectionDAG &DAG = DCI.DAG; 6740 6741 EVT VT = REMNode.getValueType(); 6742 EVT SVT = VT.getScalarType(); 6743 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6744 EVT ShSVT = ShVT.getScalarType(); 6745 6746 // If MUL is unavailable, we cannot proceed in any case. 6747 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6748 return SDValue(); 6749 6750 bool ComparingWithAllZeros = true; 6751 bool AllComparisonsWithNonZerosAreTautological = true; 6752 bool HadTautologicalLanes = false; 6753 bool AllLanesAreTautological = true; 6754 bool HadEvenDivisor = false; 6755 bool AllDivisorsArePowerOfTwo = true; 6756 bool HadTautologicalInvertedLanes = false; 6757 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6758 6759 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6760 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6761 if (CDiv->isZero()) 6762 return false; 6763 6764 const APInt &D = CDiv->getAPIntValue(); 6765 const APInt &Cmp = CCmp->getAPIntValue(); 6766 6767 ComparingWithAllZeros &= Cmp.isZero(); 6768 6769 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6770 // if C2 is not less than C1, the comparison is always false. 6771 // But we will only be able to produce the comparison that will give the 6772 // opposive tautological answer. So this lane would need to be fixed up. 6773 bool TautologicalInvertedLane = D.ule(Cmp); 6774 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6775 6776 // If all lanes are tautological (either all divisors are ones, or divisor 6777 // is not greater than the constant we are comparing with), 6778 // we will prefer to avoid the fold. 6779 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6780 HadTautologicalLanes |= TautologicalLane; 6781 AllLanesAreTautological &= TautologicalLane; 6782 6783 // If we are comparing with non-zero, we need'll need to subtract said 6784 // comparison value from the LHS. But there is no point in doing that if 6785 // every lane where we are comparing with non-zero is tautological.. 6786 if (!Cmp.isZero()) 6787 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6788 6789 // Decompose D into D0 * 2^K 6790 unsigned K = D.countr_zero(); 6791 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6792 APInt D0 = D.lshr(K); 6793 6794 // D is even if it has trailing zeros. 6795 HadEvenDivisor |= (K != 0); 6796 // D is a power-of-two if D0 is one. 6797 // If all divisors are power-of-two, we will prefer to avoid the fold. 6798 AllDivisorsArePowerOfTwo &= D0.isOne(); 6799 6800 // P = inv(D0, 2^W) 6801 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6802 unsigned W = D.getBitWidth(); 6803 APInt P = D0.multiplicativeInverse(); 6804 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6805 6806 // Q = floor((2^W - 1) u/ D) 6807 // R = ((2^W - 1) u% D) 6808 APInt Q, R; 6809 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6810 6811 // If we are comparing with zero, then that comparison constant is okay, 6812 // else it may need to be one less than that. 6813 if (Cmp.ugt(R)) 6814 Q -= 1; 6815 6816 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6817 "We are expecting that K is always less than all-ones for ShSVT"); 6818 6819 // If the lane is tautological the result can be constant-folded. 6820 if (TautologicalLane) { 6821 // Set P and K amount to a bogus values so we can try to splat them. 6822 P = 0; 6823 K = -1; 6824 // And ensure that comparison constant is tautological, 6825 // it will always compare true/false. 6826 Q = -1; 6827 } 6828 6829 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6830 KAmts.push_back( 6831 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K, /*isSigned=*/false, 6832 /*implicitTrunc=*/true), 6833 DL, ShSVT)); 6834 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6835 return true; 6836 }; 6837 6838 SDValue N = REMNode.getOperand(0); 6839 SDValue D = REMNode.getOperand(1); 6840 6841 // Collect the values from each element. 6842 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6843 return SDValue(); 6844 6845 // If all lanes are tautological, the result can be constant-folded. 6846 if (AllLanesAreTautological) 6847 return SDValue(); 6848 6849 // If this is a urem by a powers-of-two, avoid the fold since it can be 6850 // best implemented as a bit test. 6851 if (AllDivisorsArePowerOfTwo) 6852 return SDValue(); 6853 6854 SDValue PVal, KVal, QVal; 6855 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6856 if (HadTautologicalLanes) { 6857 // Try to turn PAmts into a splat, since we don't care about the values 6858 // that are currently '0'. If we can't, just keep '0'`s. 6859 turnVectorIntoSplatVector(PAmts, isNullConstant); 6860 // Try to turn KAmts into a splat, since we don't care about the values 6861 // that are currently '-1'. If we can't, change them to '0'`s. 6862 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6863 DAG.getConstant(0, DL, ShSVT)); 6864 } 6865 6866 PVal = DAG.getBuildVector(VT, DL, PAmts); 6867 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6868 QVal = DAG.getBuildVector(VT, DL, QAmts); 6869 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6870 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6871 "Expected matchBinaryPredicate to return one element for " 6872 "SPLAT_VECTORs"); 6873 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6874 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6875 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6876 } else { 6877 PVal = PAmts[0]; 6878 KVal = KAmts[0]; 6879 QVal = QAmts[0]; 6880 } 6881 6882 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6883 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6884 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6885 assert(CompTargetNode.getValueType() == N.getValueType() && 6886 "Expecting that the types on LHS and RHS of comparisons match."); 6887 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6888 } 6889 6890 // (mul N, P) 6891 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6892 Created.push_back(Op0.getNode()); 6893 6894 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6895 // divisors as a performance improvement, since rotating by 0 is a no-op. 6896 if (HadEvenDivisor) { 6897 // We need ROTR to do this. 6898 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6899 return SDValue(); 6900 // UREM: (rotr (mul N, P), K) 6901 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6902 Created.push_back(Op0.getNode()); 6903 } 6904 6905 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6906 SDValue NewCC = 6907 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6908 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6909 if (!HadTautologicalInvertedLanes) 6910 return NewCC; 6911 6912 // If any lanes previously compared always-false, the NewCC will give 6913 // always-true result for them, so we need to fixup those lanes. 6914 // Or the other way around for inequality predicate. 6915 assert(VT.isVector() && "Can/should only get here for vectors."); 6916 Created.push_back(NewCC.getNode()); 6917 6918 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6919 // if C2 is not less than C1, the comparison is always false. 6920 // But we have produced the comparison that will give the 6921 // opposive tautological answer. So these lanes would need to be fixed up. 6922 SDValue TautologicalInvertedChannels = 6923 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6924 Created.push_back(TautologicalInvertedChannels.getNode()); 6925 6926 // NOTE: we avoid letting illegal types through even if we're before legalize 6927 // ops – legalization has a hard time producing good code for this. 6928 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6929 // If we have a vector select, let's replace the comparison results in the 6930 // affected lanes with the correct tautological result. 6931 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6932 DL, SETCCVT, SETCCVT); 6933 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6934 Replacement, NewCC); 6935 } 6936 6937 // Else, we can just invert the comparison result in the appropriate lanes. 6938 // 6939 // NOTE: see the note above VSELECT above. 6940 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6941 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6942 TautologicalInvertedChannels); 6943 6944 return SDValue(); // Don't know how to lower. 6945 } 6946 6947 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6948 /// where the divisor is constant and the comparison target is zero, 6949 /// return a DAG expression that will generate the same comparison result 6950 /// using only multiplications, additions and shifts/rotations. 6951 /// Ref: "Hacker's Delight" 10-17. 6952 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6953 SDValue CompTargetNode, 6954 ISD::CondCode Cond, 6955 DAGCombinerInfo &DCI, 6956 const SDLoc &DL) const { 6957 SmallVector<SDNode *, 7> Built; 6958 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6959 DCI, DL, Built)) { 6960 assert(Built.size() <= 7 && "Max size prediction failed."); 6961 for (SDNode *N : Built) 6962 DCI.AddToWorklist(N); 6963 return Folded; 6964 } 6965 6966 return SDValue(); 6967 } 6968 6969 SDValue 6970 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6971 SDValue CompTargetNode, ISD::CondCode Cond, 6972 DAGCombinerInfo &DCI, const SDLoc &DL, 6973 SmallVectorImpl<SDNode *> &Created) const { 6974 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17. 6975 // Fold: 6976 // (seteq/ne (srem N, D), 0) 6977 // To: 6978 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6979 // 6980 // - D must be constant, with D = D0 * 2^K where D0 is odd 6981 // - P is the multiplicative inverse of D0 modulo 2^W 6982 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6983 // - Q = floor((2 * A) / (2^K)) 6984 // where W is the width of the common type of N and D. 6985 // 6986 // When D is a power of two (and thus D0 is 1), the normal 6987 // formula for A and Q don't apply, because the derivation 6988 // depends on D not dividing 2^(W-1), and thus theorem ZRS 6989 // does not apply. This specifically fails when N = INT_MIN. 6990 // 6991 // Instead, for power-of-two D, we use: 6992 // - A = 2^(W-1) 6993 // |-> Order-preserving map from [-2^(W-1), 2^(W-1) - 1] to [0,2^W - 1]) 6994 // - Q = 2^(W-K) - 1 6995 // |-> Test that the top K bits are zero after rotation 6996 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6997 "Only applicable for (in)equality comparisons."); 6998 6999 SelectionDAG &DAG = DCI.DAG; 7000 7001 EVT VT = REMNode.getValueType(); 7002 EVT SVT = VT.getScalarType(); 7003 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7004 EVT ShSVT = ShVT.getScalarType(); 7005 7006 // If we are after ops legalization, and MUL is unavailable, we can not 7007 // proceed. 7008 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 7009 return SDValue(); 7010 7011 // TODO: Could support comparing with non-zero too. 7012 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 7013 if (!CompTarget || !CompTarget->isZero()) 7014 return SDValue(); 7015 7016 bool HadIntMinDivisor = false; 7017 bool HadOneDivisor = false; 7018 bool AllDivisorsAreOnes = true; 7019 bool HadEvenDivisor = false; 7020 bool NeedToApplyOffset = false; 7021 bool AllDivisorsArePowerOfTwo = true; 7022 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 7023 7024 auto BuildSREMPattern = [&](ConstantSDNode *C) { 7025 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 7026 if (C->isZero()) 7027 return false; 7028 7029 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 7030 7031 // WARNING: this fold is only valid for positive divisors! 7032 APInt D = C->getAPIntValue(); 7033 if (D.isNegative()) 7034 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 7035 7036 HadIntMinDivisor |= D.isMinSignedValue(); 7037 7038 // If all divisors are ones, we will prefer to avoid the fold. 7039 HadOneDivisor |= D.isOne(); 7040 AllDivisorsAreOnes &= D.isOne(); 7041 7042 // Decompose D into D0 * 2^K 7043 unsigned K = D.countr_zero(); 7044 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 7045 APInt D0 = D.lshr(K); 7046 7047 if (!D.isMinSignedValue()) { 7048 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 7049 // we don't care about this lane in this fold, we'll special-handle it. 7050 HadEvenDivisor |= (K != 0); 7051 } 7052 7053 // D is a power-of-two if D0 is one. This includes INT_MIN. 7054 // If all divisors are power-of-two, we will prefer to avoid the fold. 7055 AllDivisorsArePowerOfTwo &= D0.isOne(); 7056 7057 // P = inv(D0, 2^W) 7058 // 2^W requires W + 1 bits, so we have to extend and then truncate. 7059 unsigned W = D.getBitWidth(); 7060 APInt P = D0.multiplicativeInverse(); 7061 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 7062 7063 // A = floor((2^(W - 1) - 1) / D0) & -2^K 7064 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 7065 A.clearLowBits(K); 7066 7067 if (!D.isMinSignedValue()) { 7068 // If divisor INT_MIN, then we don't care about this lane in this fold, 7069 // we'll special-handle it. 7070 NeedToApplyOffset |= A != 0; 7071 } 7072 7073 // Q = floor((2 * A) / (2^K)) 7074 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 7075 7076 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 7077 "We are expecting that A is always less than all-ones for SVT"); 7078 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 7079 "We are expecting that K is always less than all-ones for ShSVT"); 7080 7081 // If D was a power of two, apply the alternate constant derivation. 7082 if (D0.isOne()) { 7083 // A = 2^(W-1) 7084 A = APInt::getSignedMinValue(W); 7085 // - Q = 2^(W-K) - 1 7086 Q = APInt::getAllOnes(W - K).zext(W); 7087 } 7088 7089 // If the divisor is 1 the result can be constant-folded. Likewise, we 7090 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 7091 if (D.isOne()) { 7092 // Set P, A and K to a bogus values so we can try to splat them. 7093 P = 0; 7094 A = -1; 7095 K = -1; 7096 7097 // x ?% 1 == 0 <--> true <--> x u<= -1 7098 Q = -1; 7099 } 7100 7101 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 7102 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 7103 KAmts.push_back( 7104 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K, /*isSigned=*/false, 7105 /*implicitTrunc=*/true), 7106 DL, ShSVT)); 7107 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 7108 return true; 7109 }; 7110 7111 SDValue N = REMNode.getOperand(0); 7112 SDValue D = REMNode.getOperand(1); 7113 7114 // Collect the values from each element. 7115 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 7116 return SDValue(); 7117 7118 // If this is a srem by a one, avoid the fold since it can be constant-folded. 7119 if (AllDivisorsAreOnes) 7120 return SDValue(); 7121 7122 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 7123 // since it can be best implemented as a bit test. 7124 if (AllDivisorsArePowerOfTwo) 7125 return SDValue(); 7126 7127 SDValue PVal, AVal, KVal, QVal; 7128 if (D.getOpcode() == ISD::BUILD_VECTOR) { 7129 if (HadOneDivisor) { 7130 // Try to turn PAmts into a splat, since we don't care about the values 7131 // that are currently '0'. If we can't, just keep '0'`s. 7132 turnVectorIntoSplatVector(PAmts, isNullConstant); 7133 // Try to turn AAmts into a splat, since we don't care about the 7134 // values that are currently '-1'. If we can't, change them to '0'`s. 7135 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 7136 DAG.getConstant(0, DL, SVT)); 7137 // Try to turn KAmts into a splat, since we don't care about the values 7138 // that are currently '-1'. If we can't, change them to '0'`s. 7139 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 7140 DAG.getConstant(0, DL, ShSVT)); 7141 } 7142 7143 PVal = DAG.getBuildVector(VT, DL, PAmts); 7144 AVal = DAG.getBuildVector(VT, DL, AAmts); 7145 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 7146 QVal = DAG.getBuildVector(VT, DL, QAmts); 7147 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 7148 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 7149 QAmts.size() == 1 && 7150 "Expected matchUnaryPredicate to return one element for scalable " 7151 "vectors"); 7152 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 7153 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 7154 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 7155 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 7156 } else { 7157 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 7158 PVal = PAmts[0]; 7159 AVal = AAmts[0]; 7160 KVal = KAmts[0]; 7161 QVal = QAmts[0]; 7162 } 7163 7164 // (mul N, P) 7165 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 7166 Created.push_back(Op0.getNode()); 7167 7168 if (NeedToApplyOffset) { 7169 // We need ADD to do this. 7170 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 7171 return SDValue(); 7172 7173 // (add (mul N, P), A) 7174 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 7175 Created.push_back(Op0.getNode()); 7176 } 7177 7178 // Rotate right only if any divisor was even. We avoid rotates for all-odd 7179 // divisors as a performance improvement, since rotating by 0 is a no-op. 7180 if (HadEvenDivisor) { 7181 // We need ROTR to do this. 7182 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 7183 return SDValue(); 7184 // SREM: (rotr (add (mul N, P), A), K) 7185 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 7186 Created.push_back(Op0.getNode()); 7187 } 7188 7189 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 7190 SDValue Fold = 7191 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 7192 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 7193 7194 // If we didn't have lanes with INT_MIN divisor, then we're done. 7195 if (!HadIntMinDivisor) 7196 return Fold; 7197 7198 // That fold is only valid for positive divisors. Which effectively means, 7199 // it is invalid for INT_MIN divisors. So if we have such a lane, 7200 // we must fix-up results for said lanes. 7201 assert(VT.isVector() && "Can/should only get here for vectors."); 7202 7203 // NOTE: we avoid letting illegal types through even if we're before legalize 7204 // ops – legalization has a hard time producing good code for the code that 7205 // follows. 7206 if (!isOperationLegalOrCustom(ISD::SETCC, SETCCVT) || 7207 !isOperationLegalOrCustom(ISD::AND, VT) || 7208 !isCondCodeLegalOrCustom(Cond, VT.getSimpleVT()) || 7209 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 7210 return SDValue(); 7211 7212 Created.push_back(Fold.getNode()); 7213 7214 SDValue IntMin = DAG.getConstant( 7215 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 7216 SDValue IntMax = DAG.getConstant( 7217 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 7218 SDValue Zero = 7219 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 7220 7221 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 7222 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 7223 Created.push_back(DivisorIsIntMin.getNode()); 7224 7225 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 7226 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 7227 Created.push_back(Masked.getNode()); 7228 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 7229 Created.push_back(MaskedIsZero.getNode()); 7230 7231 // To produce final result we need to blend 2 vectors: 'SetCC' and 7232 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 7233 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 7234 // constant-folded, select can get lowered to a shuffle with constant mask. 7235 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 7236 MaskedIsZero, Fold); 7237 7238 return Blended; 7239 } 7240 7241 bool TargetLowering:: 7242 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 7243 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 7244 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 7245 "be a constant integer"); 7246 return true; 7247 } 7248 7249 return false; 7250 } 7251 7252 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7253 const DenormalMode &Mode) const { 7254 SDLoc DL(Op); 7255 EVT VT = Op.getValueType(); 7256 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7257 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7258 7259 // This is specifically a check for the handling of denormal inputs, not the 7260 // result. 7261 if (Mode.Input == DenormalMode::PreserveSign || 7262 Mode.Input == DenormalMode::PositiveZero) { 7263 // Test = X == 0.0 7264 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7265 } 7266 7267 // Testing it with denormal inputs to avoid wrong estimate. 7268 // 7269 // Test = fabs(X) < SmallestNormal 7270 const fltSemantics &FltSem = VT.getFltSemantics(); 7271 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 7272 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 7273 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 7274 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 7275 } 7276 7277 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 7278 bool LegalOps, bool OptForSize, 7279 NegatibleCost &Cost, 7280 unsigned Depth) const { 7281 // fneg is removable even if it has multiple uses. 7282 if (Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::VP_FNEG) { 7283 Cost = NegatibleCost::Cheaper; 7284 return Op.getOperand(0); 7285 } 7286 7287 // Don't recurse exponentially. 7288 if (Depth > SelectionDAG::MaxRecursionDepth) 7289 return SDValue(); 7290 7291 // Pre-increment recursion depth for use in recursive calls. 7292 ++Depth; 7293 const SDNodeFlags Flags = Op->getFlags(); 7294 const TargetOptions &Options = DAG.getTarget().Options; 7295 EVT VT = Op.getValueType(); 7296 unsigned Opcode = Op.getOpcode(); 7297 7298 // Don't allow anything with multiple uses unless we know it is free. 7299 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 7300 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 7301 isFPExtFree(VT, Op.getOperand(0).getValueType()); 7302 if (!IsFreeExtend) 7303 return SDValue(); 7304 } 7305 7306 auto RemoveDeadNode = [&](SDValue N) { 7307 if (N && N.getNode()->use_empty()) 7308 DAG.RemoveDeadNode(N.getNode()); 7309 }; 7310 7311 SDLoc DL(Op); 7312 7313 // Because getNegatedExpression can delete nodes we need a handle to keep 7314 // temporary nodes alive in case the recursion manages to create an identical 7315 // node. 7316 std::list<HandleSDNode> Handles; 7317 7318 switch (Opcode) { 7319 case ISD::ConstantFP: { 7320 // Don't invert constant FP values after legalization unless the target says 7321 // the negated constant is legal. 7322 bool IsOpLegal = 7323 isOperationLegal(ISD::ConstantFP, VT) || 7324 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 7325 OptForSize); 7326 7327 if (LegalOps && !IsOpLegal) 7328 break; 7329 7330 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 7331 V.changeSign(); 7332 SDValue CFP = DAG.getConstantFP(V, DL, VT); 7333 7334 // If we already have the use of the negated floating constant, it is free 7335 // to negate it even it has multiple uses. 7336 if (!Op.hasOneUse() && CFP.use_empty()) 7337 break; 7338 Cost = NegatibleCost::Neutral; 7339 return CFP; 7340 } 7341 case ISD::BUILD_VECTOR: { 7342 // Only permit BUILD_VECTOR of constants. 7343 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 7344 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 7345 })) 7346 break; 7347 7348 bool IsOpLegal = 7349 (isOperationLegal(ISD::ConstantFP, VT) && 7350 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 7351 llvm::all_of(Op->op_values(), [&](SDValue N) { 7352 return N.isUndef() || 7353 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 7354 OptForSize); 7355 }); 7356 7357 if (LegalOps && !IsOpLegal) 7358 break; 7359 7360 SmallVector<SDValue, 4> Ops; 7361 for (SDValue C : Op->op_values()) { 7362 if (C.isUndef()) { 7363 Ops.push_back(C); 7364 continue; 7365 } 7366 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 7367 V.changeSign(); 7368 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 7369 } 7370 Cost = NegatibleCost::Neutral; 7371 return DAG.getBuildVector(VT, DL, Ops); 7372 } 7373 case ISD::FADD: { 7374 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7375 break; 7376 7377 // After operation legalization, it might not be legal to create new FSUBs. 7378 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 7379 break; 7380 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7381 7382 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 7383 NegatibleCost CostX = NegatibleCost::Expensive; 7384 SDValue NegX = 7385 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7386 // Prevent this node from being deleted by the next call. 7387 if (NegX) 7388 Handles.emplace_back(NegX); 7389 7390 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 7391 NegatibleCost CostY = NegatibleCost::Expensive; 7392 SDValue NegY = 7393 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7394 7395 // We're done with the handles. 7396 Handles.clear(); 7397 7398 // Negate the X if its cost is less or equal than Y. 7399 if (NegX && (CostX <= CostY)) { 7400 Cost = CostX; 7401 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 7402 if (NegY != N) 7403 RemoveDeadNode(NegY); 7404 return N; 7405 } 7406 7407 // Negate the Y if it is not expensive. 7408 if (NegY) { 7409 Cost = CostY; 7410 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 7411 if (NegX != N) 7412 RemoveDeadNode(NegX); 7413 return N; 7414 } 7415 break; 7416 } 7417 case ISD::FSUB: { 7418 // We can't turn -(A-B) into B-A when we honor signed zeros. 7419 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7420 break; 7421 7422 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7423 // fold (fneg (fsub 0, Y)) -> Y 7424 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 7425 if (C->isZero()) { 7426 Cost = NegatibleCost::Cheaper; 7427 return Y; 7428 } 7429 7430 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 7431 Cost = NegatibleCost::Neutral; 7432 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 7433 } 7434 case ISD::FMUL: 7435 case ISD::FDIV: { 7436 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7437 7438 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 7439 NegatibleCost CostX = NegatibleCost::Expensive; 7440 SDValue NegX = 7441 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7442 // Prevent this node from being deleted by the next call. 7443 if (NegX) 7444 Handles.emplace_back(NegX); 7445 7446 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 7447 NegatibleCost CostY = NegatibleCost::Expensive; 7448 SDValue NegY = 7449 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7450 7451 // We're done with the handles. 7452 Handles.clear(); 7453 7454 // Negate the X if its cost is less or equal than Y. 7455 if (NegX && (CostX <= CostY)) { 7456 Cost = CostX; 7457 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 7458 if (NegY != N) 7459 RemoveDeadNode(NegY); 7460 return N; 7461 } 7462 7463 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 7464 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 7465 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 7466 break; 7467 7468 // Negate the Y if it is not expensive. 7469 if (NegY) { 7470 Cost = CostY; 7471 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 7472 if (NegX != N) 7473 RemoveDeadNode(NegX); 7474 return N; 7475 } 7476 break; 7477 } 7478 case ISD::FMA: 7479 case ISD::FMAD: { 7480 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7481 break; 7482 7483 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 7484 NegatibleCost CostZ = NegatibleCost::Expensive; 7485 SDValue NegZ = 7486 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 7487 // Give up if fail to negate the Z. 7488 if (!NegZ) 7489 break; 7490 7491 // Prevent this node from being deleted by the next two calls. 7492 Handles.emplace_back(NegZ); 7493 7494 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 7495 NegatibleCost CostX = NegatibleCost::Expensive; 7496 SDValue NegX = 7497 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7498 // Prevent this node from being deleted by the next call. 7499 if (NegX) 7500 Handles.emplace_back(NegX); 7501 7502 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 7503 NegatibleCost CostY = NegatibleCost::Expensive; 7504 SDValue NegY = 7505 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7506 7507 // We're done with the handles. 7508 Handles.clear(); 7509 7510 // Negate the X if its cost is less or equal than Y. 7511 if (NegX && (CostX <= CostY)) { 7512 Cost = std::min(CostX, CostZ); 7513 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 7514 if (NegY != N) 7515 RemoveDeadNode(NegY); 7516 return N; 7517 } 7518 7519 // Negate the Y if it is not expensive. 7520 if (NegY) { 7521 Cost = std::min(CostY, CostZ); 7522 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 7523 if (NegX != N) 7524 RemoveDeadNode(NegX); 7525 return N; 7526 } 7527 break; 7528 } 7529 7530 case ISD::FP_EXTEND: 7531 case ISD::FSIN: 7532 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7533 OptForSize, Cost, Depth)) 7534 return DAG.getNode(Opcode, DL, VT, NegV); 7535 break; 7536 case ISD::FP_ROUND: 7537 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7538 OptForSize, Cost, Depth)) 7539 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 7540 break; 7541 case ISD::SELECT: 7542 case ISD::VSELECT: { 7543 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS)) 7544 // iff at least one cost is cheaper and the other is neutral/cheaper 7545 SDValue LHS = Op.getOperand(1); 7546 NegatibleCost CostLHS = NegatibleCost::Expensive; 7547 SDValue NegLHS = 7548 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth); 7549 if (!NegLHS || CostLHS > NegatibleCost::Neutral) { 7550 RemoveDeadNode(NegLHS); 7551 break; 7552 } 7553 7554 // Prevent this node from being deleted by the next call. 7555 Handles.emplace_back(NegLHS); 7556 7557 SDValue RHS = Op.getOperand(2); 7558 NegatibleCost CostRHS = NegatibleCost::Expensive; 7559 SDValue NegRHS = 7560 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth); 7561 7562 // We're done with the handles. 7563 Handles.clear(); 7564 7565 if (!NegRHS || CostRHS > NegatibleCost::Neutral || 7566 (CostLHS != NegatibleCost::Cheaper && 7567 CostRHS != NegatibleCost::Cheaper)) { 7568 RemoveDeadNode(NegLHS); 7569 RemoveDeadNode(NegRHS); 7570 break; 7571 } 7572 7573 Cost = std::min(CostLHS, CostRHS); 7574 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS); 7575 } 7576 } 7577 7578 return SDValue(); 7579 } 7580 7581 //===----------------------------------------------------------------------===// 7582 // Legalization Utilities 7583 //===----------------------------------------------------------------------===// 7584 7585 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 7586 SDValue LHS, SDValue RHS, 7587 SmallVectorImpl<SDValue> &Result, 7588 EVT HiLoVT, SelectionDAG &DAG, 7589 MulExpansionKind Kind, SDValue LL, 7590 SDValue LH, SDValue RL, SDValue RH) const { 7591 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 7592 Opcode == ISD::SMUL_LOHI); 7593 7594 bool HasMULHS = (Kind == MulExpansionKind::Always) || 7595 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 7596 bool HasMULHU = (Kind == MulExpansionKind::Always) || 7597 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 7598 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 7599 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 7600 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 7601 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 7602 7603 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 7604 return false; 7605 7606 unsigned OuterBitSize = VT.getScalarSizeInBits(); 7607 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 7608 7609 // LL, LH, RL, and RH must be either all NULL or all set to a value. 7610 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 7611 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 7612 7613 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 7614 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 7615 bool Signed) -> bool { 7616 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 7617 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 7618 Hi = SDValue(Lo.getNode(), 1); 7619 return true; 7620 } 7621 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 7622 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 7623 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 7624 return true; 7625 } 7626 return false; 7627 }; 7628 7629 SDValue Lo, Hi; 7630 7631 if (!LL.getNode() && !RL.getNode() && 7632 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7633 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 7634 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 7635 } 7636 7637 if (!LL.getNode()) 7638 return false; 7639 7640 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 7641 if (DAG.MaskedValueIsZero(LHS, HighMask) && 7642 DAG.MaskedValueIsZero(RHS, HighMask)) { 7643 // The inputs are both zero-extended. 7644 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 7645 Result.push_back(Lo); 7646 Result.push_back(Hi); 7647 if (Opcode != ISD::MUL) { 7648 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7649 Result.push_back(Zero); 7650 Result.push_back(Zero); 7651 } 7652 return true; 7653 } 7654 } 7655 7656 if (!VT.isVector() && Opcode == ISD::MUL && 7657 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize && 7658 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) { 7659 // The input values are both sign-extended. 7660 // TODO non-MUL case? 7661 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 7662 Result.push_back(Lo); 7663 Result.push_back(Hi); 7664 return true; 7665 } 7666 } 7667 7668 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 7669 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl); 7670 7671 if (!LH.getNode() && !RH.getNode() && 7672 isOperationLegalOrCustom(ISD::SRL, VT) && 7673 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7674 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 7675 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 7676 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 7677 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 7678 } 7679 7680 if (!LH.getNode()) 7681 return false; 7682 7683 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 7684 return false; 7685 7686 Result.push_back(Lo); 7687 7688 if (Opcode == ISD::MUL) { 7689 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 7690 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 7691 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 7692 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 7693 Result.push_back(Hi); 7694 return true; 7695 } 7696 7697 // Compute the full width result. 7698 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 7699 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 7700 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7701 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 7702 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 7703 }; 7704 7705 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7706 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 7707 return false; 7708 7709 // This is effectively the add part of a multiply-add of half-sized operands, 7710 // so it cannot overflow. 7711 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7712 7713 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 7714 return false; 7715 7716 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7717 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7718 7719 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 7720 isOperationLegalOrCustom(ISD::ADDE, VT)); 7721 if (UseGlue) 7722 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 7723 Merge(Lo, Hi)); 7724 else 7725 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next, 7726 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 7727 7728 SDValue Carry = Next.getValue(1); 7729 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7730 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7731 7732 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7733 return false; 7734 7735 if (UseGlue) 7736 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7737 Carry); 7738 else 7739 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7740 Zero, Carry); 7741 7742 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7743 7744 if (Opcode == ISD::SMUL_LOHI) { 7745 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7746 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7747 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7748 7749 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7750 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7751 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7752 } 7753 7754 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7755 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7756 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7757 return true; 7758 } 7759 7760 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7761 SelectionDAG &DAG, MulExpansionKind Kind, 7762 SDValue LL, SDValue LH, SDValue RL, 7763 SDValue RH) const { 7764 SmallVector<SDValue, 2> Result; 7765 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7766 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7767 DAG, Kind, LL, LH, RL, RH); 7768 if (Ok) { 7769 assert(Result.size() == 2); 7770 Lo = Result[0]; 7771 Hi = Result[1]; 7772 } 7773 return Ok; 7774 } 7775 7776 // Optimize unsigned division or remainder by constants for types twice as large 7777 // as a legal VT. 7778 // 7779 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder 7780 // can be computed 7781 // as: 7782 // Sum += __builtin_uadd_overflow(Lo, High, &Sum); 7783 // Remainder = Sum % Constant 7784 // This is based on "Remainder by Summing Digits" from Hacker's Delight. 7785 // 7786 // For division, we can compute the remainder using the algorithm described 7787 // above, subtract it from the dividend to get an exact multiple of Constant. 7788 // Then multiply that exact multiply by the multiplicative inverse modulo 7789 // (1 << (BitWidth / 2)) to get the quotient. 7790 7791 // If Constant is even, we can shift right the dividend and the divisor by the 7792 // number of trailing zeros in Constant before applying the remainder algorithm. 7793 // If we're after the quotient, we can subtract this value from the shifted 7794 // dividend and multiply by the multiplicative inverse of the shifted divisor. 7795 // If we want the remainder, we shift the value left by the number of trailing 7796 // zeros and add the bits that were shifted out of the dividend. 7797 bool TargetLowering::expandDIVREMByConstant(SDNode *N, 7798 SmallVectorImpl<SDValue> &Result, 7799 EVT HiLoVT, SelectionDAG &DAG, 7800 SDValue LL, SDValue LH) const { 7801 unsigned Opcode = N->getOpcode(); 7802 EVT VT = N->getValueType(0); 7803 7804 // TODO: Support signed division/remainder. 7805 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM) 7806 return false; 7807 assert( 7808 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) && 7809 "Unexpected opcode"); 7810 7811 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7812 if (!CN) 7813 return false; 7814 7815 APInt Divisor = CN->getAPIntValue(); 7816 unsigned BitWidth = Divisor.getBitWidth(); 7817 unsigned HBitWidth = BitWidth / 2; 7818 assert(VT.getScalarSizeInBits() == BitWidth && 7819 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs"); 7820 7821 // Divisor needs to less than (1 << HBitWidth). 7822 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth); 7823 if (Divisor.uge(HalfMaxPlus1)) 7824 return false; 7825 7826 // We depend on the UREM by constant optimization in DAGCombiner that requires 7827 // high multiply. 7828 if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) && 7829 !isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT)) 7830 return false; 7831 7832 // Don't expand if optimizing for size. 7833 if (DAG.shouldOptForSize()) 7834 return false; 7835 7836 // Early out for 0 or 1 divisors. 7837 if (Divisor.ule(1)) 7838 return false; 7839 7840 // If the divisor is even, shift it until it becomes odd. 7841 unsigned TrailingZeros = 0; 7842 if (!Divisor[0]) { 7843 TrailingZeros = Divisor.countr_zero(); 7844 Divisor.lshrInPlace(TrailingZeros); 7845 } 7846 7847 SDLoc dl(N); 7848 SDValue Sum; 7849 SDValue PartialRem; 7850 7851 // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and 7852 // then add in the carry. 7853 // TODO: If we can't split it in half, we might be able to split into 3 or 7854 // more pieces using a smaller bit width. 7855 if (HalfMaxPlus1.urem(Divisor).isOne()) { 7856 assert(!LL == !LH && "Expected both input halves or no input halves!"); 7857 if (!LL) 7858 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT); 7859 7860 // Shift the input by the number of TrailingZeros in the divisor. The 7861 // shifted out bits will be added to the remainder later. 7862 if (TrailingZeros) { 7863 // Save the shifted off bits if we need the remainder. 7864 if (Opcode != ISD::UDIV) { 7865 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7866 PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL, 7867 DAG.getConstant(Mask, dl, HiLoVT)); 7868 } 7869 7870 LL = DAG.getNode( 7871 ISD::OR, dl, HiLoVT, 7872 DAG.getNode(ISD::SRL, dl, HiLoVT, LL, 7873 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)), 7874 DAG.getNode(ISD::SHL, dl, HiLoVT, LH, 7875 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, 7876 HiLoVT, dl))); 7877 LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH, 7878 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7879 } 7880 7881 // Use uaddo_carry if we can, otherwise use a compare to detect overflow. 7882 EVT SetCCType = 7883 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT); 7884 if (isOperationLegalOrCustom(ISD::UADDO_CARRY, HiLoVT)) { 7885 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType); 7886 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH); 7887 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum, 7888 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1)); 7889 } else { 7890 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH); 7891 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT); 7892 // If the boolean for the target is 0 or 1, we can add the setcc result 7893 // directly. 7894 if (getBooleanContents(HiLoVT) == 7895 TargetLoweringBase::ZeroOrOneBooleanContent) 7896 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT); 7897 else 7898 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT), 7899 DAG.getConstant(0, dl, HiLoVT)); 7900 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry); 7901 } 7902 } 7903 7904 // If we didn't find a sum, we can't do the expansion. 7905 if (!Sum) 7906 return false; 7907 7908 // Perform a HiLoVT urem on the Sum using truncated divisor. 7909 SDValue RemL = 7910 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum, 7911 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT)); 7912 SDValue RemH = DAG.getConstant(0, dl, HiLoVT); 7913 7914 if (Opcode != ISD::UREM) { 7915 // Subtract the remainder from the shifted dividend. 7916 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH); 7917 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH); 7918 7919 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem); 7920 7921 // Multiply by the multiplicative inverse of the divisor modulo 7922 // (1 << BitWidth). 7923 APInt MulFactor = Divisor.multiplicativeInverse(); 7924 7925 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend, 7926 DAG.getConstant(MulFactor, dl, VT)); 7927 7928 // Split the quotient into low and high parts. 7929 SDValue QuotL, QuotH; 7930 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT); 7931 Result.push_back(QuotL); 7932 Result.push_back(QuotH); 7933 } 7934 7935 if (Opcode != ISD::UDIV) { 7936 // If we shifted the input, shift the remainder left and add the bits we 7937 // shifted off the input. 7938 if (TrailingZeros) { 7939 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7940 RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL, 7941 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7942 RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem); 7943 } 7944 Result.push_back(RemL); 7945 Result.push_back(DAG.getConstant(0, dl, HiLoVT)); 7946 } 7947 7948 return true; 7949 } 7950 7951 // Check that (every element of) Z is undef or not an exact multiple of BW. 7952 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7953 return ISD::matchUnaryPredicate( 7954 Z, 7955 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7956 true); 7957 } 7958 7959 static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG) { 7960 EVT VT = Node->getValueType(0); 7961 SDValue ShX, ShY; 7962 SDValue ShAmt, InvShAmt; 7963 SDValue X = Node->getOperand(0); 7964 SDValue Y = Node->getOperand(1); 7965 SDValue Z = Node->getOperand(2); 7966 SDValue Mask = Node->getOperand(3); 7967 SDValue VL = Node->getOperand(4); 7968 7969 unsigned BW = VT.getScalarSizeInBits(); 7970 bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL; 7971 SDLoc DL(SDValue(Node, 0)); 7972 7973 EVT ShVT = Z.getValueType(); 7974 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7975 // fshl: X << C | Y >> (BW - C) 7976 // fshr: X << (BW - C) | Y >> C 7977 // where C = Z % BW is not zero 7978 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7979 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7980 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL); 7981 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask, 7982 VL); 7983 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask, 7984 VL); 7985 } else { 7986 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7987 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7988 SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT); 7989 if (isPowerOf2_32(BW)) { 7990 // Z % BW -> Z & (BW - 1) 7991 ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL); 7992 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7993 SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z, 7994 DAG.getAllOnesConstant(DL, ShVT), Mask, VL); 7995 InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL); 7996 } else { 7997 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7998 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7999 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL); 8000 } 8001 8002 SDValue One = DAG.getConstant(1, DL, ShVT); 8003 if (IsFSHL) { 8004 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL); 8005 SDValue ShY1 = DAG.getNode(ISD::VP_SRL, DL, VT, Y, One, Mask, VL); 8006 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, ShY1, InvShAmt, Mask, VL); 8007 } else { 8008 SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL); 8009 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL); 8010 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, ShAmt, Mask, VL); 8011 } 8012 } 8013 return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL); 8014 } 8015 8016 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 8017 SelectionDAG &DAG) const { 8018 if (Node->isVPOpcode()) 8019 return expandVPFunnelShift(Node, DAG); 8020 8021 EVT VT = Node->getValueType(0); 8022 8023 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 8024 !isOperationLegalOrCustom(ISD::SRL, VT) || 8025 !isOperationLegalOrCustom(ISD::SUB, VT) || 8026 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 8027 return SDValue(); 8028 8029 SDValue X = Node->getOperand(0); 8030 SDValue Y = Node->getOperand(1); 8031 SDValue Z = Node->getOperand(2); 8032 8033 unsigned BW = VT.getScalarSizeInBits(); 8034 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 8035 SDLoc DL(SDValue(Node, 0)); 8036 8037 EVT ShVT = Z.getValueType(); 8038 8039 // If a funnel shift in the other direction is more supported, use it. 8040 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 8041 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 8042 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 8043 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 8044 // fshl X, Y, Z -> fshr X, Y, -Z 8045 // fshr X, Y, Z -> fshl X, Y, -Z 8046 SDValue Zero = DAG.getConstant(0, DL, ShVT); 8047 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 8048 } else { 8049 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 8050 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 8051 SDValue One = DAG.getConstant(1, DL, ShVT); 8052 if (IsFSHL) { 8053 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 8054 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 8055 } else { 8056 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 8057 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 8058 } 8059 Z = DAG.getNOT(DL, Z, ShVT); 8060 } 8061 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 8062 } 8063 8064 SDValue ShX, ShY; 8065 SDValue ShAmt, InvShAmt; 8066 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 8067 // fshl: X << C | Y >> (BW - C) 8068 // fshr: X << (BW - C) | Y >> C 8069 // where C = Z % BW is not zero 8070 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 8071 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 8072 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 8073 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 8074 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 8075 } else { 8076 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 8077 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 8078 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 8079 if (isPowerOf2_32(BW)) { 8080 // Z % BW -> Z & (BW - 1) 8081 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 8082 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 8083 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 8084 } else { 8085 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 8086 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 8087 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 8088 } 8089 8090 SDValue One = DAG.getConstant(1, DL, ShVT); 8091 if (IsFSHL) { 8092 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 8093 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 8094 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 8095 } else { 8096 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 8097 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 8098 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 8099 } 8100 } 8101 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 8102 } 8103 8104 // TODO: Merge with expandFunnelShift. 8105 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 8106 SelectionDAG &DAG) const { 8107 EVT VT = Node->getValueType(0); 8108 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 8109 bool IsLeft = Node->getOpcode() == ISD::ROTL; 8110 SDValue Op0 = Node->getOperand(0); 8111 SDValue Op1 = Node->getOperand(1); 8112 SDLoc DL(SDValue(Node, 0)); 8113 8114 EVT ShVT = Op1.getValueType(); 8115 SDValue Zero = DAG.getConstant(0, DL, ShVT); 8116 8117 // If a rotate in the other direction is more supported, use it. 8118 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 8119 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 8120 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 8121 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 8122 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 8123 } 8124 8125 if (!AllowVectorOps && VT.isVector() && 8126 (!isOperationLegalOrCustom(ISD::SHL, VT) || 8127 !isOperationLegalOrCustom(ISD::SRL, VT) || 8128 !isOperationLegalOrCustom(ISD::SUB, VT) || 8129 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 8130 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 8131 return SDValue(); 8132 8133 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 8134 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 8135 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 8136 SDValue ShVal; 8137 SDValue HsVal; 8138 if (isPowerOf2_32(EltSizeInBits)) { 8139 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 8140 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 8141 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 8142 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 8143 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 8144 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 8145 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 8146 } else { 8147 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 8148 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 8149 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 8150 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 8151 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 8152 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 8153 SDValue One = DAG.getConstant(1, DL, ShVT); 8154 HsVal = 8155 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 8156 } 8157 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 8158 } 8159 8160 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 8161 SelectionDAG &DAG) const { 8162 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 8163 EVT VT = Node->getValueType(0); 8164 unsigned VTBits = VT.getScalarSizeInBits(); 8165 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 8166 8167 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 8168 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 8169 SDValue ShOpLo = Node->getOperand(0); 8170 SDValue ShOpHi = Node->getOperand(1); 8171 SDValue ShAmt = Node->getOperand(2); 8172 EVT ShAmtVT = ShAmt.getValueType(); 8173 EVT ShAmtCCVT = 8174 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 8175 SDLoc dl(Node); 8176 8177 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 8178 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 8179 // away during isel. 8180 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 8181 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 8182 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 8183 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 8184 : DAG.getConstant(0, dl, VT); 8185 8186 SDValue Tmp2, Tmp3; 8187 if (IsSHL) { 8188 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 8189 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 8190 } else { 8191 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 8192 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 8193 } 8194 8195 // If the shift amount is larger or equal than the width of a part we don't 8196 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 8197 // values for large shift amounts. 8198 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 8199 DAG.getConstant(VTBits, dl, ShAmtVT)); 8200 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 8201 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 8202 8203 if (IsSHL) { 8204 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8205 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8206 } else { 8207 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8208 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8209 } 8210 } 8211 8212 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 8213 SelectionDAG &DAG) const { 8214 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8215 SDValue Src = Node->getOperand(OpNo); 8216 EVT SrcVT = Src.getValueType(); 8217 EVT DstVT = Node->getValueType(0); 8218 SDLoc dl(SDValue(Node, 0)); 8219 8220 // FIXME: Only f32 to i64 conversions are supported. 8221 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 8222 return false; 8223 8224 if (Node->isStrictFPOpcode()) 8225 // When a NaN is converted to an integer a trap is allowed. We can't 8226 // use this expansion here because it would eliminate that trap. Other 8227 // traps are also allowed and cannot be eliminated. See 8228 // IEEE 754-2008 sec 5.8. 8229 return false; 8230 8231 // Expand f32 -> i64 conversion 8232 // This algorithm comes from compiler-rt's implementation of fixsfdi: 8233 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 8234 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 8235 EVT IntVT = SrcVT.changeTypeToInteger(); 8236 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 8237 8238 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 8239 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 8240 SDValue Bias = DAG.getConstant(127, dl, IntVT); 8241 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 8242 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 8243 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 8244 8245 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 8246 8247 SDValue ExponentBits = DAG.getNode( 8248 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 8249 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 8250 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 8251 8252 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 8253 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 8254 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 8255 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 8256 8257 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 8258 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 8259 DAG.getConstant(0x00800000, dl, IntVT)); 8260 8261 R = DAG.getZExtOrTrunc(R, dl, DstVT); 8262 8263 R = DAG.getSelectCC( 8264 dl, Exponent, ExponentLoBit, 8265 DAG.getNode(ISD::SHL, dl, DstVT, R, 8266 DAG.getZExtOrTrunc( 8267 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 8268 dl, IntShVT)), 8269 DAG.getNode(ISD::SRL, dl, DstVT, R, 8270 DAG.getZExtOrTrunc( 8271 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 8272 dl, IntShVT)), 8273 ISD::SETGT); 8274 8275 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 8276 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 8277 8278 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 8279 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 8280 return true; 8281 } 8282 8283 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 8284 SDValue &Chain, 8285 SelectionDAG &DAG) const { 8286 SDLoc dl(SDValue(Node, 0)); 8287 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8288 SDValue Src = Node->getOperand(OpNo); 8289 8290 EVT SrcVT = Src.getValueType(); 8291 EVT DstVT = Node->getValueType(0); 8292 EVT SetCCVT = 8293 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8294 EVT DstSetCCVT = 8295 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8296 8297 // Only expand vector types if we have the appropriate vector bit operations. 8298 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 8299 ISD::FP_TO_SINT; 8300 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 8301 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 8302 return false; 8303 8304 // If the maximum float value is smaller then the signed integer range, 8305 // the destination signmask can't be represented by the float, so we can 8306 // just use FP_TO_SINT directly. 8307 const fltSemantics &APFSem = SrcVT.getFltSemantics(); 8308 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 8309 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 8310 if (APFloat::opOverflow & 8311 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 8312 if (Node->isStrictFPOpcode()) { 8313 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8314 { Node->getOperand(0), Src }); 8315 Chain = Result.getValue(1); 8316 } else 8317 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8318 return true; 8319 } 8320 8321 // Don't expand it if there isn't cheap fsub instruction. 8322 if (!isOperationLegalOrCustom( 8323 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 8324 return false; 8325 8326 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8327 SDValue Sel; 8328 8329 if (Node->isStrictFPOpcode()) { 8330 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8331 Node->getOperand(0), /*IsSignaling*/ true); 8332 Chain = Sel.getValue(1); 8333 } else { 8334 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 8335 } 8336 8337 bool Strict = Node->isStrictFPOpcode() || 8338 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 8339 8340 if (Strict) { 8341 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 8342 // signmask then offset (the result of which should be fully representable). 8343 // Sel = Src < 0x8000000000000000 8344 // FltOfs = select Sel, 0, 0x8000000000000000 8345 // IntOfs = select Sel, 0, 0x8000000000000000 8346 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8347 8348 // TODO: Should any fast-math-flags be set for the FSUB? 8349 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 8350 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8351 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8352 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 8353 DAG.getConstant(0, dl, DstVT), 8354 DAG.getConstant(SignMask, dl, DstVT)); 8355 SDValue SInt; 8356 if (Node->isStrictFPOpcode()) { 8357 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 8358 { Chain, Src, FltOfs }); 8359 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8360 { Val.getValue(1), Val }); 8361 Chain = SInt.getValue(1); 8362 } else { 8363 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 8364 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 8365 } 8366 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8367 } else { 8368 // Expand based on maximum range of FP_TO_SINT: 8369 // True = fp_to_sint(Src) 8370 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 8371 // Result = select (Src < 0x8000000000000000), True, False 8372 8373 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8374 // TODO: Should any fast-math-flags be set for the FSUB? 8375 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 8376 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 8377 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 8378 DAG.getConstant(SignMask, dl, DstVT)); 8379 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8380 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 8381 } 8382 return true; 8383 } 8384 8385 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 8386 SDValue &Chain, SelectionDAG &DAG) const { 8387 // This transform is not correct for converting 0 when rounding mode is set 8388 // to round toward negative infinity which will produce -0.0. So disable 8389 // under strictfp. 8390 if (Node->isStrictFPOpcode()) 8391 return false; 8392 8393 SDValue Src = Node->getOperand(0); 8394 EVT SrcVT = Src.getValueType(); 8395 EVT DstVT = Node->getValueType(0); 8396 8397 // If the input is known to be non-negative and SINT_TO_FP is legal then use 8398 // it. 8399 if (Node->getFlags().hasNonNeg() && 8400 isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT)) { 8401 Result = 8402 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0)); 8403 return true; 8404 } 8405 8406 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 8407 return false; 8408 8409 // Only expand vector types if we have the appropriate vector bit 8410 // operations. 8411 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 8412 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 8413 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 8414 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 8415 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 8416 return false; 8417 8418 SDLoc dl(SDValue(Node, 0)); 8419 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 8420 8421 // Implementation of unsigned i64 to f64 following the algorithm in 8422 // __floatundidf in compiler_rt. This implementation performs rounding 8423 // correctly in all rounding modes with the exception of converting 0 8424 // when rounding toward negative infinity. In that case the fsub will 8425 // produce -0.0. This will be added to +0.0 and produce -0.0 which is 8426 // incorrect. 8427 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 8428 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 8429 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT); 8430 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 8431 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 8432 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 8433 8434 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 8435 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 8436 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 8437 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 8438 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 8439 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 8440 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 8441 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 8442 return true; 8443 } 8444 8445 SDValue 8446 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 8447 SelectionDAG &DAG) const { 8448 unsigned Opcode = Node->getOpcode(); 8449 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 8450 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 8451 "Wrong opcode"); 8452 8453 if (Node->getFlags().hasNoNaNs()) { 8454 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 8455 EVT VT = Node->getValueType(0); 8456 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) || 8457 !isOperationLegalOrCustom(ISD::VSELECT, VT)) && 8458 VT.isVector()) 8459 return SDValue(); 8460 SDValue Op1 = Node->getOperand(0); 8461 SDValue Op2 = Node->getOperand(1); 8462 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 8463 // Copy FMF flags, but always set the no-signed-zeros flag 8464 // as this is implied by the FMINNUM/FMAXNUM semantics. 8465 SelCC->setFlags(Node->getFlags() | SDNodeFlags::NoSignedZeros); 8466 return SelCC; 8467 } 8468 8469 return SDValue(); 8470 } 8471 8472 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 8473 SelectionDAG &DAG) const { 8474 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG)) 8475 return Expanded; 8476 8477 EVT VT = Node->getValueType(0); 8478 if (VT.isScalableVector()) 8479 report_fatal_error( 8480 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 8481 8482 SDLoc dl(Node); 8483 unsigned NewOp = 8484 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 8485 8486 if (isOperationLegalOrCustom(NewOp, VT)) { 8487 SDValue Quiet0 = Node->getOperand(0); 8488 SDValue Quiet1 = Node->getOperand(1); 8489 8490 if (!Node->getFlags().hasNoNaNs()) { 8491 // Insert canonicalizes if it's possible we need to quiet to get correct 8492 // sNaN behavior. 8493 if (!DAG.isKnownNeverSNaN(Quiet0)) { 8494 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 8495 Node->getFlags()); 8496 } 8497 if (!DAG.isKnownNeverSNaN(Quiet1)) { 8498 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 8499 Node->getFlags()); 8500 } 8501 } 8502 8503 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 8504 } 8505 8506 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 8507 // instead if there are no NaNs and there can't be an incompatible zero 8508 // compare: at least one operand isn't +/-0, or there are no signed-zeros. 8509 if ((Node->getFlags().hasNoNaNs() || 8510 (DAG.isKnownNeverNaN(Node->getOperand(0)) && 8511 DAG.isKnownNeverNaN(Node->getOperand(1)))) && 8512 (Node->getFlags().hasNoSignedZeros() || 8513 DAG.isKnownNeverZeroFloat(Node->getOperand(0)) || 8514 DAG.isKnownNeverZeroFloat(Node->getOperand(1)))) { 8515 unsigned IEEE2018Op = 8516 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 8517 if (isOperationLegalOrCustom(IEEE2018Op, VT)) 8518 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 8519 Node->getOperand(1), Node->getFlags()); 8520 } 8521 8522 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 8523 return SelCC; 8524 8525 return SDValue(); 8526 } 8527 8528 SDValue TargetLowering::expandFMINIMUM_FMAXIMUM(SDNode *N, 8529 SelectionDAG &DAG) const { 8530 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG)) 8531 return Expanded; 8532 8533 SDLoc DL(N); 8534 SDValue LHS = N->getOperand(0); 8535 SDValue RHS = N->getOperand(1); 8536 unsigned Opc = N->getOpcode(); 8537 EVT VT = N->getValueType(0); 8538 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8539 bool IsMax = Opc == ISD::FMAXIMUM; 8540 SDNodeFlags Flags = N->getFlags(); 8541 8542 // First, implement comparison not propagating NaN. If no native fmin or fmax 8543 // available, use plain select with setcc instead. 8544 SDValue MinMax; 8545 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 8546 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM; 8547 8548 // FIXME: We should probably define fminnum/fmaxnum variants with correct 8549 // signed zero behavior. 8550 bool MinMaxMustRespectOrderedZero = false; 8551 8552 if (isOperationLegalOrCustom(CompOpcIeee, VT)) { 8553 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags); 8554 MinMaxMustRespectOrderedZero = true; 8555 } else if (isOperationLegalOrCustom(CompOpc, VT)) { 8556 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags); 8557 } else { 8558 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8559 return DAG.UnrollVectorOp(N); 8560 8561 // NaN (if exists) will be propagated later, so orderness doesn't matter. 8562 SDValue Compare = 8563 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT); 8564 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags); 8565 } 8566 8567 // Propagate any NaN of both operands 8568 if (!N->getFlags().hasNoNaNs() && 8569 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) { 8570 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(), 8571 APFloat::getNaN(VT.getFltSemantics())); 8572 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO), 8573 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags); 8574 } 8575 8576 // fminimum/fmaximum requires -0.0 less than +0.0 8577 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() && 8578 !DAG.isKnownNeverZeroFloat(RHS) && !DAG.isKnownNeverZeroFloat(LHS)) { 8579 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax, 8580 DAG.getConstantFP(0.0, DL, VT), ISD::SETOEQ); 8581 SDValue TestZero = 8582 DAG.getTargetConstant(IsMax ? fcPosZero : fcNegZero, DL, MVT::i32); 8583 SDValue LCmp = DAG.getSelect( 8584 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, LHS, TestZero), LHS, 8585 MinMax, Flags); 8586 SDValue RCmp = DAG.getSelect( 8587 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, RHS, TestZero), RHS, 8588 LCmp, Flags); 8589 MinMax = DAG.getSelect(DL, VT, IsZero, RCmp, MinMax, Flags); 8590 } 8591 8592 return MinMax; 8593 } 8594 8595 SDValue TargetLowering::expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *Node, 8596 SelectionDAG &DAG) const { 8597 SDLoc DL(Node); 8598 SDValue LHS = Node->getOperand(0); 8599 SDValue RHS = Node->getOperand(1); 8600 unsigned Opc = Node->getOpcode(); 8601 EVT VT = Node->getValueType(0); 8602 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8603 bool IsMax = Opc == ISD::FMAXIMUMNUM; 8604 const TargetOptions &Options = DAG.getTarget().Options; 8605 SDNodeFlags Flags = Node->getFlags(); 8606 8607 unsigned NewOp = 8608 Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 8609 8610 if (isOperationLegalOrCustom(NewOp, VT)) { 8611 if (!Flags.hasNoNaNs()) { 8612 // Insert canonicalizes if it's possible we need to quiet to get correct 8613 // sNaN behavior. 8614 if (!DAG.isKnownNeverSNaN(LHS)) { 8615 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags); 8616 } 8617 if (!DAG.isKnownNeverSNaN(RHS)) { 8618 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags); 8619 } 8620 } 8621 8622 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags); 8623 } 8624 8625 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has 8626 // same behaviors for all of other cases: +0.0 vs -0.0 included. 8627 if (Flags.hasNoNaNs() || 8628 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) { 8629 unsigned IEEE2019Op = 8630 Opc == ISD::FMINIMUMNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 8631 if (isOperationLegalOrCustom(IEEE2019Op, VT)) 8632 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags); 8633 } 8634 8635 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return 8636 // either one for +0.0 vs -0.0. 8637 if ((Flags.hasNoNaNs() || 8638 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) && 8639 (Flags.hasNoSignedZeros() || DAG.isKnownNeverZeroFloat(LHS) || 8640 DAG.isKnownNeverZeroFloat(RHS))) { 8641 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM; 8642 if (isOperationLegalOrCustom(IEEE2008Op, VT)) 8643 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags); 8644 } 8645 8646 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8647 return DAG.UnrollVectorOp(Node); 8648 8649 // If only one operand is NaN, override it with another operand. 8650 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) { 8651 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO); 8652 } 8653 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) { 8654 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO); 8655 } 8656 8657 SDValue MinMax = 8658 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT); 8659 // If MinMax is NaN, let's quiet it. 8660 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS) && 8661 !DAG.isKnownNeverNaN(RHS)) { 8662 MinMax = DAG.getNode(ISD::FCANONICALIZE, DL, VT, MinMax, Flags); 8663 } 8664 8665 // Fixup signed zero behavior. 8666 if (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros() || 8667 DAG.isKnownNeverZeroFloat(LHS) || DAG.isKnownNeverZeroFloat(RHS)) { 8668 return MinMax; 8669 } 8670 SDValue TestZero = 8671 DAG.getTargetConstant(IsMax ? fcPosZero : fcNegZero, DL, MVT::i32); 8672 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax, 8673 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ); 8674 SDValue LCmp = DAG.getSelect( 8675 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, LHS, TestZero), LHS, 8676 MinMax, Flags); 8677 SDValue RCmp = DAG.getSelect( 8678 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, RHS, TestZero), RHS, LCmp, 8679 Flags); 8680 return DAG.getSelect(DL, VT, IsZero, RCmp, MinMax, Flags); 8681 } 8682 8683 /// Returns a true value if if this FPClassTest can be performed with an ordered 8684 /// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns 8685 /// std::nullopt if it cannot be performed as a compare with 0. 8686 static std::optional<bool> isFCmpEqualZero(FPClassTest Test, 8687 const fltSemantics &Semantics, 8688 const MachineFunction &MF) { 8689 FPClassTest OrderedMask = Test & ~fcNan; 8690 FPClassTest NanTest = Test & fcNan; 8691 bool IsOrdered = NanTest == fcNone; 8692 bool IsUnordered = NanTest == fcNan; 8693 8694 // Skip cases that are testing for only a qnan or snan. 8695 if (!IsOrdered && !IsUnordered) 8696 return std::nullopt; 8697 8698 if (OrderedMask == fcZero && 8699 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE) 8700 return IsOrdered; 8701 if (OrderedMask == (fcZero | fcSubnormal) && 8702 MF.getDenormalMode(Semantics).inputsAreZero()) 8703 return IsOrdered; 8704 return std::nullopt; 8705 } 8706 8707 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 8708 const FPClassTest OrigTestMask, 8709 SDNodeFlags Flags, const SDLoc &DL, 8710 SelectionDAG &DAG) const { 8711 EVT OperandVT = Op.getValueType(); 8712 assert(OperandVT.isFloatingPoint()); 8713 FPClassTest Test = OrigTestMask; 8714 8715 // Degenerated cases. 8716 if (Test == fcNone) 8717 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 8718 if (Test == fcAllFlags) 8719 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 8720 8721 // PPC double double is a pair of doubles, of which the higher part determines 8722 // the value class. 8723 if (OperandVT == MVT::ppcf128) { 8724 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 8725 DAG.getConstant(1, DL, MVT::i32)); 8726 OperandVT = MVT::f64; 8727 } 8728 8729 // Floating-point type properties. 8730 EVT ScalarFloatVT = OperandVT.getScalarType(); 8731 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 8732 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 8733 bool IsF80 = (ScalarFloatVT == MVT::f80); 8734 8735 // Some checks can be implemented using float comparisons, if floating point 8736 // exceptions are ignored. 8737 if (Flags.hasNoFPExcept() && 8738 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 8739 FPClassTest FPTestMask = Test; 8740 bool IsInvertedFP = false; 8741 8742 if (FPClassTest InvertedFPCheck = 8743 invertFPClassTestIfSimpler(FPTestMask, true)) { 8744 FPTestMask = InvertedFPCheck; 8745 IsInvertedFP = true; 8746 } 8747 8748 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ; 8749 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ; 8750 8751 // See if we can fold an | fcNan into an unordered compare. 8752 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan; 8753 8754 // Can't fold the ordered check if we're only testing for snan or qnan 8755 // individually. 8756 if ((FPTestMask & fcNan) != fcNan) 8757 OrderedFPTestMask = FPTestMask; 8758 8759 const bool IsOrdered = FPTestMask == OrderedFPTestMask; 8760 8761 if (std::optional<bool> IsCmp0 = 8762 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction()); 8763 IsCmp0 && (isCondCodeLegalOrCustom( 8764 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode, 8765 OperandVT.getScalarType().getSimpleVT()))) { 8766 8767 // If denormals could be implicitly treated as 0, this is not equivalent 8768 // to a compare with 0 since it will also be true for denormals. 8769 return DAG.getSetCC(DL, ResultVT, Op, 8770 DAG.getConstantFP(0.0, DL, OperandVT), 8771 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode); 8772 } 8773 8774 if (FPTestMask == fcNan && 8775 isCondCodeLegalOrCustom(IsInvertedFP ? ISD::SETO : ISD::SETUO, 8776 OperandVT.getScalarType().getSimpleVT())) 8777 return DAG.getSetCC(DL, ResultVT, Op, Op, 8778 IsInvertedFP ? ISD::SETO : ISD::SETUO); 8779 8780 bool IsOrderedInf = FPTestMask == fcInf; 8781 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) && 8782 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode 8783 : UnorderedCmpOpcode, 8784 OperandVT.getScalarType().getSimpleVT()) && 8785 isOperationLegalOrCustom(ISD::FABS, OperandVT.getScalarType()) && 8786 (isOperationLegal(ISD::ConstantFP, OperandVT.getScalarType()) || 8787 (OperandVT.isVector() && 8788 isOperationLegalOrCustom(ISD::BUILD_VECTOR, OperandVT)))) { 8789 // isinf(x) --> fabs(x) == inf 8790 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8791 SDValue Inf = 8792 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT); 8793 return DAG.getSetCC(DL, ResultVT, Abs, Inf, 8794 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode); 8795 } 8796 8797 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) && 8798 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode 8799 : UnorderedCmpOpcode, 8800 OperandVT.getSimpleVT())) { 8801 // isposinf(x) --> x == inf 8802 // isneginf(x) --> x == -inf 8803 // isposinf(x) || nan --> x u== inf 8804 // isneginf(x) || nan --> x u== -inf 8805 8806 SDValue Inf = DAG.getConstantFP( 8807 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL, 8808 OperandVT); 8809 return DAG.getSetCC(DL, ResultVT, Op, Inf, 8810 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode); 8811 } 8812 8813 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) { 8814 // TODO: Could handle ordered case, but it produces worse code for 8815 // x86. Maybe handle ordered if fabs is free? 8816 8817 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT; 8818 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT; 8819 8820 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp, 8821 OperandVT.getScalarType().getSimpleVT())) { 8822 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal 8823 8824 // TODO: Maybe only makes sense if fabs is free. Integer test of 8825 // exponent bits seems better for x86. 8826 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8827 SDValue SmallestNormal = DAG.getConstantFP( 8828 APFloat::getSmallestNormalized(Semantics), DL, OperandVT); 8829 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, 8830 IsOrdered ? OrderedOp : UnorderedOp); 8831 } 8832 } 8833 8834 if (FPTestMask == fcNormal) { 8835 // TODO: Handle unordered 8836 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT; 8837 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE; 8838 8839 if (isCondCodeLegalOrCustom(IsFiniteOp, 8840 OperandVT.getScalarType().getSimpleVT()) && 8841 isCondCodeLegalOrCustom(IsNormalOp, 8842 OperandVT.getScalarType().getSimpleVT()) && 8843 isFAbsFree(OperandVT)) { 8844 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal) 8845 SDValue Inf = 8846 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT); 8847 SDValue SmallestNormal = DAG.getConstantFP( 8848 APFloat::getSmallestNormalized(Semantics), DL, OperandVT); 8849 8850 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8851 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp); 8852 SDValue IsNormal = 8853 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp); 8854 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND; 8855 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal); 8856 } 8857 } 8858 } 8859 8860 // Some checks may be represented as inversion of simpler check, for example 8861 // "inf|normal|subnormal|zero" => !"nan". 8862 bool IsInverted = false; 8863 8864 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) { 8865 Test = InvertedCheck; 8866 IsInverted = true; 8867 } 8868 8869 // In the general case use integer operations. 8870 unsigned BitSize = OperandVT.getScalarSizeInBits(); 8871 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 8872 if (OperandVT.isVector()) 8873 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 8874 OperandVT.getVectorElementCount()); 8875 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 8876 8877 // Various masks. 8878 APInt SignBit = APInt::getSignMask(BitSize); 8879 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 8880 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 8881 const unsigned ExplicitIntBitInF80 = 63; 8882 APInt ExpMask = Inf; 8883 if (IsF80) 8884 ExpMask.clearBit(ExplicitIntBitInF80); 8885 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 8886 APInt QNaNBitMask = 8887 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 8888 APInt InvertionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits()); 8889 8890 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 8891 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 8892 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 8893 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 8894 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 8895 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 8896 8897 SDValue Res; 8898 const auto appendResult = [&](SDValue PartialRes) { 8899 if (PartialRes) { 8900 if (Res) 8901 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 8902 else 8903 Res = PartialRes; 8904 } 8905 }; 8906 8907 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 8908 const auto getIntBitIsSet = [&]() -> SDValue { 8909 if (!IntBitIsSetV) { 8910 APInt IntBitMask(BitSize, 0); 8911 IntBitMask.setBit(ExplicitIntBitInF80); 8912 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 8913 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 8914 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 8915 } 8916 return IntBitIsSetV; 8917 }; 8918 8919 // Split the value into sign bit and absolute value. 8920 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 8921 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 8922 DAG.getConstant(0, DL, IntVT), ISD::SETLT); 8923 8924 // Tests that involve more than one class should be processed first. 8925 SDValue PartialRes; 8926 8927 if (IsF80) 8928 ; // Detect finite numbers of f80 by checking individual classes because 8929 // they have different settings of the explicit integer bit. 8930 else if ((Test & fcFinite) == fcFinite) { 8931 // finite(V) ==> abs(V) < exp_mask 8932 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8933 Test &= ~fcFinite; 8934 } else if ((Test & fcFinite) == fcPosFinite) { 8935 // finite(V) && V > 0 ==> V < exp_mask 8936 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 8937 Test &= ~fcPosFinite; 8938 } else if ((Test & fcFinite) == fcNegFinite) { 8939 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 8940 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8941 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8942 Test &= ~fcNegFinite; 8943 } 8944 appendResult(PartialRes); 8945 8946 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) { 8947 // fcZero | fcSubnormal => test all exponent bits are 0 8948 // TODO: Handle sign bit specific cases 8949 if (PartialCheck == (fcZero | fcSubnormal)) { 8950 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV); 8951 SDValue ExpIsZero = 8952 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 8953 appendResult(ExpIsZero); 8954 Test &= ~PartialCheck & fcAllFlags; 8955 } 8956 } 8957 8958 // Check for individual classes. 8959 8960 if (unsigned PartialCheck = Test & fcZero) { 8961 if (PartialCheck == fcPosZero) 8962 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 8963 else if (PartialCheck == fcZero) 8964 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 8965 else // ISD::fcNegZero 8966 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 8967 appendResult(PartialRes); 8968 } 8969 8970 if (unsigned PartialCheck = Test & fcSubnormal) { 8971 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 8972 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 8973 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 8974 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 8975 SDValue VMinusOneV = 8976 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 8977 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 8978 if (PartialCheck == fcNegSubnormal) 8979 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8980 appendResult(PartialRes); 8981 } 8982 8983 if (unsigned PartialCheck = Test & fcInf) { 8984 if (PartialCheck == fcPosInf) 8985 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 8986 else if (PartialCheck == fcInf) 8987 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 8988 else { // ISD::fcNegInf 8989 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 8990 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 8991 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 8992 } 8993 appendResult(PartialRes); 8994 } 8995 8996 if (unsigned PartialCheck = Test & fcNan) { 8997 APInt InfWithQnanBit = Inf | QNaNBitMask; 8998 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 8999 if (PartialCheck == fcNan) { 9000 // isnan(V) ==> abs(V) > int(inf) 9001 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 9002 if (IsF80) { 9003 // Recognize unsupported values as NaNs for compatibility with glibc. 9004 // In them (exp(V)==0) == int_bit. 9005 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 9006 SDValue ExpIsZero = 9007 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 9008 SDValue IsPseudo = 9009 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 9010 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 9011 } 9012 } else if (PartialCheck == fcQNan) { 9013 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 9014 PartialRes = 9015 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 9016 } else { // ISD::fcSNan 9017 // issignaling(V) ==> abs(V) > unsigned(Inf) && 9018 // abs(V) < (unsigned(Inf) | quiet_bit) 9019 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 9020 SDValue IsNotQnan = 9021 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 9022 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 9023 } 9024 appendResult(PartialRes); 9025 } 9026 9027 if (unsigned PartialCheck = Test & fcNormal) { 9028 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 9029 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 9030 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 9031 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 9032 APInt ExpLimit = ExpMask - ExpLSB; 9033 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 9034 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 9035 if (PartialCheck == fcNegNormal) 9036 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 9037 else if (PartialCheck == fcPosNormal) { 9038 SDValue PosSignV = 9039 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 9040 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 9041 } 9042 if (IsF80) 9043 PartialRes = 9044 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 9045 appendResult(PartialRes); 9046 } 9047 9048 if (!Res) 9049 return DAG.getConstant(IsInverted, DL, ResultVT); 9050 if (IsInverted) 9051 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 9052 return Res; 9053 } 9054 9055 // Only expand vector types if we have the appropriate vector bit operations. 9056 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 9057 assert(VT.isVector() && "Expected vector type"); 9058 unsigned Len = VT.getScalarSizeInBits(); 9059 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 9060 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 9061 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 9062 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 9063 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 9064 } 9065 9066 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 9067 SDLoc dl(Node); 9068 EVT VT = Node->getValueType(0); 9069 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9070 SDValue Op = Node->getOperand(0); 9071 unsigned Len = VT.getScalarSizeInBits(); 9072 assert(VT.isInteger() && "CTPOP not implemented for this type."); 9073 9074 // TODO: Add support for irregular type lengths. 9075 if (!(Len <= 128 && Len % 8 == 0)) 9076 return SDValue(); 9077 9078 // Only expand vector types if we have the appropriate vector bit operations. 9079 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 9080 return SDValue(); 9081 9082 // This is the "best" algorithm from 9083 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 9084 SDValue Mask55 = 9085 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 9086 SDValue Mask33 = 9087 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 9088 SDValue Mask0F = 9089 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 9090 9091 // v = v - ((v >> 1) & 0x55555555...) 9092 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 9093 DAG.getNode(ISD::AND, dl, VT, 9094 DAG.getNode(ISD::SRL, dl, VT, Op, 9095 DAG.getConstant(1, dl, ShVT)), 9096 Mask55)); 9097 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 9098 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 9099 DAG.getNode(ISD::AND, dl, VT, 9100 DAG.getNode(ISD::SRL, dl, VT, Op, 9101 DAG.getConstant(2, dl, ShVT)), 9102 Mask33)); 9103 // v = (v + (v >> 4)) & 0x0F0F0F0F... 9104 Op = DAG.getNode(ISD::AND, dl, VT, 9105 DAG.getNode(ISD::ADD, dl, VT, Op, 9106 DAG.getNode(ISD::SRL, dl, VT, Op, 9107 DAG.getConstant(4, dl, ShVT))), 9108 Mask0F); 9109 9110 if (Len <= 8) 9111 return Op; 9112 9113 // Avoid the multiply if we only have 2 bytes to add. 9114 // TODO: Only doing this for scalars because vectors weren't as obviously 9115 // improved. 9116 if (Len == 16 && !VT.isVector()) { 9117 // v = (v + (v >> 8)) & 0x00FF; 9118 return DAG.getNode(ISD::AND, dl, VT, 9119 DAG.getNode(ISD::ADD, dl, VT, Op, 9120 DAG.getNode(ISD::SRL, dl, VT, Op, 9121 DAG.getConstant(8, dl, ShVT))), 9122 DAG.getConstant(0xFF, dl, VT)); 9123 } 9124 9125 // v = (v * 0x01010101...) >> (Len - 8) 9126 SDValue V; 9127 if (isOperationLegalOrCustomOrPromote( 9128 ISD::MUL, getTypeToTransformTo(*DAG.getContext(), VT))) { 9129 SDValue Mask01 = 9130 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 9131 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01); 9132 } else { 9133 V = Op; 9134 for (unsigned Shift = 8; Shift < Len; Shift *= 2) { 9135 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl); 9136 V = DAG.getNode(ISD::ADD, dl, VT, V, 9137 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC)); 9138 } 9139 } 9140 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT)); 9141 } 9142 9143 SDValue TargetLowering::expandVPCTPOP(SDNode *Node, SelectionDAG &DAG) const { 9144 SDLoc dl(Node); 9145 EVT VT = Node->getValueType(0); 9146 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9147 SDValue Op = Node->getOperand(0); 9148 SDValue Mask = Node->getOperand(1); 9149 SDValue VL = Node->getOperand(2); 9150 unsigned Len = VT.getScalarSizeInBits(); 9151 assert(VT.isInteger() && "VP_CTPOP not implemented for this type."); 9152 9153 // TODO: Add support for irregular type lengths. 9154 if (!(Len <= 128 && Len % 8 == 0)) 9155 return SDValue(); 9156 9157 // This is same algorithm of expandCTPOP from 9158 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 9159 SDValue Mask55 = 9160 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 9161 SDValue Mask33 = 9162 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 9163 SDValue Mask0F = 9164 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 9165 9166 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5; 9167 9168 // v = v - ((v >> 1) & 0x55555555...) 9169 Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT, 9170 DAG.getNode(ISD::VP_SRL, dl, VT, Op, 9171 DAG.getConstant(1, dl, ShVT), Mask, VL), 9172 Mask55, Mask, VL); 9173 Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL); 9174 9175 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 9176 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL); 9177 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, 9178 DAG.getNode(ISD::VP_SRL, dl, VT, Op, 9179 DAG.getConstant(2, dl, ShVT), Mask, VL), 9180 Mask33, Mask, VL); 9181 Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL); 9182 9183 // v = (v + (v >> 4)) & 0x0F0F0F0F... 9184 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(4, dl, ShVT), 9185 Mask, VL), 9186 Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL); 9187 Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL); 9188 9189 if (Len <= 8) 9190 return Op; 9191 9192 // v = (v * 0x01010101...) >> (Len - 8) 9193 SDValue V; 9194 if (isOperationLegalOrCustomOrPromote( 9195 ISD::VP_MUL, getTypeToTransformTo(*DAG.getContext(), VT))) { 9196 SDValue Mask01 = 9197 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 9198 V = DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL); 9199 } else { 9200 V = Op; 9201 for (unsigned Shift = 8; Shift < Len; Shift *= 2) { 9202 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl); 9203 V = DAG.getNode(ISD::VP_ADD, dl, VT, V, 9204 DAG.getNode(ISD::VP_SHL, dl, VT, V, ShiftC, Mask, VL), 9205 Mask, VL); 9206 } 9207 } 9208 return DAG.getNode(ISD::VP_SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT), 9209 Mask, VL); 9210 } 9211 9212 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 9213 SDLoc dl(Node); 9214 EVT VT = Node->getValueType(0); 9215 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9216 SDValue Op = Node->getOperand(0); 9217 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9218 9219 // If the non-ZERO_UNDEF version is supported we can use that instead. 9220 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 9221 isOperationLegalOrCustom(ISD::CTLZ, VT)) 9222 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 9223 9224 // If the ZERO_UNDEF version is supported use that and handle the zero case. 9225 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 9226 EVT SetCCVT = 9227 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9228 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 9229 SDValue Zero = DAG.getConstant(0, dl, VT); 9230 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 9231 return DAG.getSelect(dl, VT, SrcIsZero, 9232 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 9233 } 9234 9235 // Only expand vector types if we have the appropriate vector bit operations. 9236 // This includes the operations needed to expand CTPOP if it isn't supported. 9237 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 9238 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 9239 !canExpandVectorCTPOP(*this, VT)) || 9240 !isOperationLegalOrCustom(ISD::SRL, VT) || 9241 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 9242 return SDValue(); 9243 9244 // for now, we do this: 9245 // x = x | (x >> 1); 9246 // x = x | (x >> 2); 9247 // ... 9248 // x = x | (x >>16); 9249 // x = x | (x >>32); // for 64-bit input 9250 // return popcount(~x); 9251 // 9252 // Ref: "Hacker's Delight" by Henry Warren 9253 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 9254 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 9255 Op = DAG.getNode(ISD::OR, dl, VT, Op, 9256 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 9257 } 9258 Op = DAG.getNOT(dl, Op, VT); 9259 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 9260 } 9261 9262 SDValue TargetLowering::expandVPCTLZ(SDNode *Node, SelectionDAG &DAG) const { 9263 SDLoc dl(Node); 9264 EVT VT = Node->getValueType(0); 9265 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9266 SDValue Op = Node->getOperand(0); 9267 SDValue Mask = Node->getOperand(1); 9268 SDValue VL = Node->getOperand(2); 9269 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9270 9271 // do this: 9272 // x = x | (x >> 1); 9273 // x = x | (x >> 2); 9274 // ... 9275 // x = x | (x >>16); 9276 // x = x | (x >>32); // for 64-bit input 9277 // return popcount(~x); 9278 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 9279 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 9280 Op = DAG.getNode(ISD::VP_OR, dl, VT, Op, 9281 DAG.getNode(ISD::VP_SRL, dl, VT, Op, Tmp, Mask, VL), Mask, 9282 VL); 9283 } 9284 Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getAllOnesConstant(dl, VT), 9285 Mask, VL); 9286 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL); 9287 } 9288 9289 SDValue TargetLowering::CTTZTableLookup(SDNode *Node, SelectionDAG &DAG, 9290 const SDLoc &DL, EVT VT, SDValue Op, 9291 unsigned BitWidth) const { 9292 if (BitWidth != 32 && BitWidth != 64) 9293 return SDValue(); 9294 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U) 9295 : APInt(64, 0x0218A392CD3D5DBFULL); 9296 const DataLayout &TD = DAG.getDataLayout(); 9297 MachinePointerInfo PtrInfo = 9298 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()); 9299 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth); 9300 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 9301 SDValue Lookup = DAG.getNode( 9302 ISD::SRL, DL, VT, 9303 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg), 9304 DAG.getConstant(DeBruijn, DL, VT)), 9305 DAG.getConstant(ShiftAmt, DL, VT)); 9306 Lookup = DAG.getSExtOrTrunc(Lookup, DL, getPointerTy(TD)); 9307 9308 SmallVector<uint8_t> Table(BitWidth, 0); 9309 for (unsigned i = 0; i < BitWidth; i++) { 9310 APInt Shl = DeBruijn.shl(i); 9311 APInt Lshr = Shl.lshr(ShiftAmt); 9312 Table[Lshr.getZExtValue()] = i; 9313 } 9314 9315 // Create a ConstantArray in Constant Pool 9316 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table); 9317 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD), 9318 TD.getPrefTypeAlign(CA->getType())); 9319 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(), 9320 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL), 9321 PtrInfo, MVT::i8); 9322 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF) 9323 return ExtLoad; 9324 9325 EVT SetCCVT = 9326 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9327 SDValue Zero = DAG.getConstant(0, DL, VT); 9328 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ); 9329 return DAG.getSelect(DL, VT, SrcIsZero, 9330 DAG.getConstant(BitWidth, DL, VT), ExtLoad); 9331 } 9332 9333 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 9334 SDLoc dl(Node); 9335 EVT VT = Node->getValueType(0); 9336 SDValue Op = Node->getOperand(0); 9337 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9338 9339 // If the non-ZERO_UNDEF version is supported we can use that instead. 9340 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 9341 isOperationLegalOrCustom(ISD::CTTZ, VT)) 9342 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 9343 9344 // If the ZERO_UNDEF version is supported use that and handle the zero case. 9345 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 9346 EVT SetCCVT = 9347 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9348 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 9349 SDValue Zero = DAG.getConstant(0, dl, VT); 9350 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 9351 return DAG.getSelect(dl, VT, SrcIsZero, 9352 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 9353 } 9354 9355 // Only expand vector types if we have the appropriate vector bit operations. 9356 // This includes the operations needed to expand CTPOP if it isn't supported. 9357 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 9358 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 9359 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 9360 !canExpandVectorCTPOP(*this, VT)) || 9361 !isOperationLegalOrCustom(ISD::SUB, VT) || 9362 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 9363 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 9364 return SDValue(); 9365 9366 // Emit Table Lookup if ISD::CTLZ and ISD::CTPOP are not legal. 9367 if (!VT.isVector() && isOperationExpand(ISD::CTPOP, VT) && 9368 !isOperationLegal(ISD::CTLZ, VT)) 9369 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt)) 9370 return V; 9371 9372 // for now, we use: { return popcount(~x & (x - 1)); } 9373 // unless the target has ctlz but not ctpop, in which case we use: 9374 // { return 32 - nlz(~x & (x-1)); } 9375 // Ref: "Hacker's Delight" by Henry Warren 9376 SDValue Tmp = DAG.getNode( 9377 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 9378 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 9379 9380 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 9381 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 9382 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 9383 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 9384 } 9385 9386 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 9387 } 9388 9389 SDValue TargetLowering::expandVPCTTZ(SDNode *Node, SelectionDAG &DAG) const { 9390 SDValue Op = Node->getOperand(0); 9391 SDValue Mask = Node->getOperand(1); 9392 SDValue VL = Node->getOperand(2); 9393 SDLoc dl(Node); 9394 EVT VT = Node->getValueType(0); 9395 9396 // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1)) 9397 SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op, 9398 DAG.getAllOnesConstant(dl, VT), Mask, VL); 9399 SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op, 9400 DAG.getConstant(1, dl, VT), Mask, VL); 9401 SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL); 9402 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL); 9403 } 9404 9405 SDValue TargetLowering::expandVPCTTZElements(SDNode *N, 9406 SelectionDAG &DAG) const { 9407 // %cond = to_bool_vec %source 9408 // %splat = splat /*val=*/VL 9409 // %tz = step_vector 9410 // %v = vp.select %cond, /*true=*/tz, /*false=*/%splat 9411 // %r = vp.reduce.umin %v 9412 SDLoc DL(N); 9413 SDValue Source = N->getOperand(0); 9414 SDValue Mask = N->getOperand(1); 9415 SDValue EVL = N->getOperand(2); 9416 EVT SrcVT = Source.getValueType(); 9417 EVT ResVT = N->getValueType(0); 9418 EVT ResVecVT = 9419 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount()); 9420 9421 // Convert to boolean vector. 9422 if (SrcVT.getScalarType() != MVT::i1) { 9423 SDValue AllZero = DAG.getConstant(0, DL, SrcVT); 9424 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 9425 SrcVT.getVectorElementCount()); 9426 Source = DAG.getNode(ISD::VP_SETCC, DL, SrcVT, Source, AllZero, 9427 DAG.getCondCode(ISD::SETNE), Mask, EVL); 9428 } 9429 9430 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT); 9431 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL); 9432 SDValue StepVec = DAG.getStepVector(DL, ResVecVT); 9433 SDValue Select = 9434 DAG.getNode(ISD::VP_SELECT, DL, ResVecVT, Source, StepVec, Splat, EVL); 9435 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL); 9436 } 9437 9438 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 9439 bool IsNegative) const { 9440 SDLoc dl(N); 9441 EVT VT = N->getValueType(0); 9442 SDValue Op = N->getOperand(0); 9443 9444 // abs(x) -> smax(x,sub(0,x)) 9445 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 9446 isOperationLegal(ISD::SMAX, VT)) { 9447 SDValue Zero = DAG.getConstant(0, dl, VT); 9448 Op = DAG.getFreeze(Op); 9449 return DAG.getNode(ISD::SMAX, dl, VT, Op, 9450 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9451 } 9452 9453 // abs(x) -> umin(x,sub(0,x)) 9454 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 9455 isOperationLegal(ISD::UMIN, VT)) { 9456 SDValue Zero = DAG.getConstant(0, dl, VT); 9457 Op = DAG.getFreeze(Op); 9458 return DAG.getNode(ISD::UMIN, dl, VT, Op, 9459 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9460 } 9461 9462 // 0 - abs(x) -> smin(x, sub(0,x)) 9463 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 9464 isOperationLegal(ISD::SMIN, VT)) { 9465 SDValue Zero = DAG.getConstant(0, dl, VT); 9466 Op = DAG.getFreeze(Op); 9467 return DAG.getNode(ISD::SMIN, dl, VT, Op, 9468 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9469 } 9470 9471 // Only expand vector types if we have the appropriate vector operations. 9472 if (VT.isVector() && 9473 (!isOperationLegalOrCustom(ISD::SRA, VT) || 9474 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 9475 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 9476 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 9477 return SDValue(); 9478 9479 Op = DAG.getFreeze(Op); 9480 SDValue Shift = DAG.getNode( 9481 ISD::SRA, dl, VT, Op, 9482 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl)); 9483 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 9484 9485 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 9486 if (!IsNegative) 9487 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 9488 9489 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 9490 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 9491 } 9492 9493 SDValue TargetLowering::expandABD(SDNode *N, SelectionDAG &DAG) const { 9494 SDLoc dl(N); 9495 EVT VT = N->getValueType(0); 9496 SDValue LHS = DAG.getFreeze(N->getOperand(0)); 9497 SDValue RHS = DAG.getFreeze(N->getOperand(1)); 9498 bool IsSigned = N->getOpcode() == ISD::ABDS; 9499 9500 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs)) 9501 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs)) 9502 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX; 9503 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN; 9504 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) { 9505 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS); 9506 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS); 9507 return DAG.getNode(ISD::SUB, dl, VT, Max, Min); 9508 } 9509 9510 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs)) 9511 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) 9512 return DAG.getNode(ISD::OR, dl, VT, 9513 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS), 9514 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS)); 9515 9516 // If the subtract doesn't overflow then just use abs(sub()) 9517 // NOTE: don't use frozen operands for value tracking. 9518 bool IsNonNegative = DAG.SignBitIsZero(N->getOperand(1)) && 9519 DAG.SignBitIsZero(N->getOperand(0)); 9520 9521 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, N->getOperand(0), 9522 N->getOperand(1))) 9523 return DAG.getNode(ISD::ABS, dl, VT, 9524 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS)); 9525 9526 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, N->getOperand(1), 9527 N->getOperand(0))) 9528 return DAG.getNode(ISD::ABS, dl, VT, 9529 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS)); 9530 9531 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9532 ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT; 9533 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC); 9534 9535 // Branchless expansion iff cmp result is allbits: 9536 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs))) 9537 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs))) 9538 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 9539 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 9540 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp); 9541 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor); 9542 } 9543 9544 // Similar to the branchless expansion, use the (sign-extended) usubo overflow 9545 // flag if the (scalar) type is illegal as this is more likely to legalize 9546 // cleanly: 9547 // abdu(lhs, rhs) -> sub(xor(sub(lhs, rhs), uof(lhs, rhs)), uof(lhs, rhs)) 9548 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT)) { 9549 SDValue USubO = 9550 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS}); 9551 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1)); 9552 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp); 9553 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp); 9554 } 9555 9556 // FIXME: Should really try to split the vector in case it's legal on a 9557 // subvector. 9558 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 9559 return DAG.UnrollVectorOp(N); 9560 9561 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9562 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9563 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS), 9564 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS)); 9565 } 9566 9567 SDValue TargetLowering::expandAVG(SDNode *N, SelectionDAG &DAG) const { 9568 SDLoc dl(N); 9569 EVT VT = N->getValueType(0); 9570 SDValue LHS = N->getOperand(0); 9571 SDValue RHS = N->getOperand(1); 9572 9573 unsigned Opc = N->getOpcode(); 9574 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU; 9575 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS; 9576 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB; 9577 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR; 9578 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL; 9579 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9580 assert((Opc == ISD::AVGFLOORS || Opc == ISD::AVGCEILS || 9581 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) && 9582 "Unknown AVG node"); 9583 9584 // If the operands are already extended, we can add+shift. 9585 bool IsExt = 9586 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 && 9587 DAG.ComputeNumSignBits(RHS) >= 2) || 9588 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 && 9589 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1); 9590 if (IsExt) { 9591 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS); 9592 if (!IsFloor) 9593 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT)); 9594 return DAG.getNode(ShiftOpc, dl, VT, Sum, 9595 DAG.getShiftAmountConstant(1, VT, dl)); 9596 } 9597 9598 // For scalars, see if we can efficiently extend/truncate to use add+shift. 9599 if (VT.isScalarInteger()) { 9600 unsigned BW = VT.getScalarSizeInBits(); 9601 EVT ExtVT = VT.getIntegerVT(*DAG.getContext(), 2 * BW); 9602 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) { 9603 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS); 9604 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS); 9605 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS); 9606 if (!IsFloor) 9607 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg, 9608 DAG.getConstant(1, dl, ExtVT)); 9609 // Just use SRL as we will be truncating away the extended sign bits. 9610 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg, 9611 DAG.getShiftAmountConstant(1, ExtVT, dl)); 9612 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg); 9613 } 9614 } 9615 9616 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1)) 9617 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT)) { 9618 SDValue UAddWithOverflow = 9619 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS}); 9620 9621 SDValue Sum = UAddWithOverflow.getValue(0); 9622 SDValue Overflow = UAddWithOverflow.getValue(1); 9623 9624 // Right shift the sum by 1 9625 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum, 9626 DAG.getShiftAmountConstant(1, VT, dl)); 9627 9628 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow); 9629 SDValue OverflowShl = DAG.getNode( 9630 ISD::SHL, dl, VT, ZeroExtOverflow, 9631 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl)); 9632 9633 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl); 9634 } 9635 9636 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1)) 9637 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1)) 9638 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1)) 9639 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1)) 9640 LHS = DAG.getFreeze(LHS); 9641 RHS = DAG.getFreeze(RHS); 9642 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS); 9643 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 9644 SDValue Shift = 9645 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl)); 9646 return DAG.getNode(SumOpc, dl, VT, Sign, Shift); 9647 } 9648 9649 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 9650 SDLoc dl(N); 9651 EVT VT = N->getValueType(0); 9652 SDValue Op = N->getOperand(0); 9653 9654 if (!VT.isSimple()) 9655 return SDValue(); 9656 9657 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9658 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9659 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9660 default: 9661 return SDValue(); 9662 case MVT::i16: 9663 // Use a rotate by 8. This can be further expanded if necessary. 9664 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9665 case MVT::i32: 9666 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9667 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op, 9668 DAG.getConstant(0xFF00, dl, VT)); 9669 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT)); 9670 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9671 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 9672 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9673 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9674 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9675 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9676 case MVT::i64: 9677 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9678 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op, 9679 DAG.getConstant(255ULL<<8, dl, VT)); 9680 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT)); 9681 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op, 9682 DAG.getConstant(255ULL<<16, dl, VT)); 9683 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT)); 9684 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op, 9685 DAG.getConstant(255ULL<<24, dl, VT)); 9686 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT)); 9687 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9688 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 9689 DAG.getConstant(255ULL<<24, dl, VT)); 9690 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9691 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 9692 DAG.getConstant(255ULL<<16, dl, VT)); 9693 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 9694 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 9695 DAG.getConstant(255ULL<<8, dl, VT)); 9696 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9697 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 9698 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 9699 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9700 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9701 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 9702 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9703 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 9704 } 9705 } 9706 9707 SDValue TargetLowering::expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const { 9708 SDLoc dl(N); 9709 EVT VT = N->getValueType(0); 9710 SDValue Op = N->getOperand(0); 9711 SDValue Mask = N->getOperand(1); 9712 SDValue EVL = N->getOperand(2); 9713 9714 if (!VT.isSimple()) 9715 return SDValue(); 9716 9717 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9718 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9719 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9720 default: 9721 return SDValue(); 9722 case MVT::i16: 9723 Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9724 Mask, EVL); 9725 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9726 Mask, EVL); 9727 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL); 9728 case MVT::i32: 9729 Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9730 Mask, EVL); 9731 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT), 9732 Mask, EVL); 9733 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT), 9734 Mask, EVL); 9735 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9736 Mask, EVL); 9737 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9738 DAG.getConstant(0xFF00, dl, VT), Mask, EVL); 9739 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9740 Mask, EVL); 9741 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9742 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9743 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9744 case MVT::i64: 9745 Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9746 Mask, EVL); 9747 Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9748 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9749 Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT), 9750 Mask, EVL); 9751 Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9752 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9753 Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT), 9754 Mask, EVL); 9755 Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9756 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9757 Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT), 9758 Mask, EVL); 9759 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9760 Mask, EVL); 9761 Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4, 9762 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9763 Tmp3 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9764 Mask, EVL); 9765 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3, 9766 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9767 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT), 9768 Mask, EVL); 9769 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9770 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9771 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9772 Mask, EVL); 9773 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL); 9774 Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL); 9775 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9776 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9777 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL); 9778 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9779 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL); 9780 } 9781 } 9782 9783 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9784 SDLoc dl(N); 9785 EVT VT = N->getValueType(0); 9786 SDValue Op = N->getOperand(0); 9787 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9788 unsigned Sz = VT.getScalarSizeInBits(); 9789 9790 SDValue Tmp, Tmp2, Tmp3; 9791 9792 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9793 // and finally the i1 pairs. 9794 // TODO: We can easily support i4/i2 legal types if any target ever does. 9795 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9796 // Create the masks - repeating the pattern every byte. 9797 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9798 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9799 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9800 9801 // BSWAP if the type is wider than a single byte. 9802 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 9803 9804 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9805 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 9806 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 9807 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 9808 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 9809 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9810 9811 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9812 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 9813 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 9814 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 9815 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 9816 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9817 9818 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9819 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 9820 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 9821 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 9822 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 9823 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9824 return Tmp; 9825 } 9826 9827 Tmp = DAG.getConstant(0, dl, VT); 9828 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 9829 if (I < J) 9830 Tmp2 = 9831 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 9832 else 9833 Tmp2 = 9834 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 9835 9836 APInt Shift = APInt::getOneBitSet(Sz, J); 9837 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 9838 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 9839 } 9840 9841 return Tmp; 9842 } 9843 9844 SDValue TargetLowering::expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9845 assert(N->getOpcode() == ISD::VP_BITREVERSE); 9846 9847 SDLoc dl(N); 9848 EVT VT = N->getValueType(0); 9849 SDValue Op = N->getOperand(0); 9850 SDValue Mask = N->getOperand(1); 9851 SDValue EVL = N->getOperand(2); 9852 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9853 unsigned Sz = VT.getScalarSizeInBits(); 9854 9855 SDValue Tmp, Tmp2, Tmp3; 9856 9857 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9858 // and finally the i1 pairs. 9859 // TODO: We can easily support i4/i2 legal types if any target ever does. 9860 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9861 // Create the masks - repeating the pattern every byte. 9862 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9863 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9864 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9865 9866 // BSWAP if the type is wider than a single byte. 9867 Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op); 9868 9869 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9870 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT), 9871 Mask, EVL); 9872 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9873 DAG.getConstant(Mask4, dl, VT), Mask, EVL); 9874 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT), 9875 Mask, EVL); 9876 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT), 9877 Mask, EVL); 9878 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9879 9880 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9881 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT), 9882 Mask, EVL); 9883 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9884 DAG.getConstant(Mask2, dl, VT), Mask, EVL); 9885 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT), 9886 Mask, EVL); 9887 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT), 9888 Mask, EVL); 9889 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9890 9891 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9892 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT), 9893 Mask, EVL); 9894 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9895 DAG.getConstant(Mask1, dl, VT), Mask, EVL); 9896 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT), 9897 Mask, EVL); 9898 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT), 9899 Mask, EVL); 9900 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9901 return Tmp; 9902 } 9903 return SDValue(); 9904 } 9905 9906 std::pair<SDValue, SDValue> 9907 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 9908 SelectionDAG &DAG) const { 9909 SDLoc SL(LD); 9910 SDValue Chain = LD->getChain(); 9911 SDValue BasePTR = LD->getBasePtr(); 9912 EVT SrcVT = LD->getMemoryVT(); 9913 EVT DstVT = LD->getValueType(0); 9914 ISD::LoadExtType ExtType = LD->getExtensionType(); 9915 9916 if (SrcVT.isScalableVector()) 9917 report_fatal_error("Cannot scalarize scalable vector loads"); 9918 9919 unsigned NumElem = SrcVT.getVectorNumElements(); 9920 9921 EVT SrcEltVT = SrcVT.getScalarType(); 9922 EVT DstEltVT = DstVT.getScalarType(); 9923 9924 // A vector must always be stored in memory as-is, i.e. without any padding 9925 // between the elements, since various code depend on it, e.g. in the 9926 // handling of a bitcast of a vector type to int, which may be done with a 9927 // vector store followed by an integer load. A vector that does not have 9928 // elements that are byte-sized must therefore be stored as an integer 9929 // built out of the extracted vector elements. 9930 if (!SrcEltVT.isByteSized()) { 9931 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 9932 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 9933 9934 unsigned NumSrcBits = SrcVT.getSizeInBits(); 9935 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 9936 9937 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 9938 SDValue SrcEltBitMask = DAG.getConstant( 9939 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 9940 9941 // Load the whole vector and avoid masking off the top bits as it makes 9942 // the codegen worse. 9943 SDValue Load = 9944 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 9945 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 9946 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9947 9948 SmallVector<SDValue, 8> Vals; 9949 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9950 unsigned ShiftIntoIdx = 9951 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 9952 SDValue ShiftAmount = DAG.getShiftAmountConstant( 9953 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL); 9954 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 9955 SDValue Elt = 9956 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 9957 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 9958 9959 if (ExtType != ISD::NON_EXTLOAD) { 9960 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 9961 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 9962 } 9963 9964 Vals.push_back(Scalar); 9965 } 9966 9967 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9968 return std::make_pair(Value, Load.getValue(1)); 9969 } 9970 9971 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 9972 assert(SrcEltVT.isByteSized()); 9973 9974 SmallVector<SDValue, 8> Vals; 9975 SmallVector<SDValue, 8> LoadChains; 9976 9977 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9978 SDValue ScalarLoad = 9979 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 9980 LD->getPointerInfo().getWithOffset(Idx * Stride), 9981 SrcEltVT, LD->getOriginalAlign(), 9982 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9983 9984 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride)); 9985 9986 Vals.push_back(ScalarLoad.getValue(0)); 9987 LoadChains.push_back(ScalarLoad.getValue(1)); 9988 } 9989 9990 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 9991 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9992 9993 return std::make_pair(Value, NewChain); 9994 } 9995 9996 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 9997 SelectionDAG &DAG) const { 9998 SDLoc SL(ST); 9999 10000 SDValue Chain = ST->getChain(); 10001 SDValue BasePtr = ST->getBasePtr(); 10002 SDValue Value = ST->getValue(); 10003 EVT StVT = ST->getMemoryVT(); 10004 10005 if (StVT.isScalableVector()) 10006 report_fatal_error("Cannot scalarize scalable vector stores"); 10007 10008 // The type of the data we want to save 10009 EVT RegVT = Value.getValueType(); 10010 EVT RegSclVT = RegVT.getScalarType(); 10011 10012 // The type of data as saved in memory. 10013 EVT MemSclVT = StVT.getScalarType(); 10014 10015 unsigned NumElem = StVT.getVectorNumElements(); 10016 10017 // A vector must always be stored in memory as-is, i.e. without any padding 10018 // between the elements, since various code depend on it, e.g. in the 10019 // handling of a bitcast of a vector type to int, which may be done with a 10020 // vector store followed by an integer load. A vector that does not have 10021 // elements that are byte-sized must therefore be stored as an integer 10022 // built out of the extracted vector elements. 10023 if (!MemSclVT.isByteSized()) { 10024 unsigned NumBits = StVT.getSizeInBits(); 10025 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 10026 10027 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 10028 10029 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 10030 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 10031 DAG.getVectorIdxConstant(Idx, SL)); 10032 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 10033 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 10034 unsigned ShiftIntoIdx = 10035 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 10036 SDValue ShiftAmount = 10037 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 10038 SDValue ShiftedElt = 10039 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 10040 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 10041 } 10042 10043 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 10044 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 10045 ST->getAAInfo()); 10046 } 10047 10048 // Store Stride in bytes 10049 unsigned Stride = MemSclVT.getSizeInBits() / 8; 10050 assert(Stride && "Zero stride!"); 10051 // Extract each of the elements from the original vector and save them into 10052 // memory individually. 10053 SmallVector<SDValue, 8> Stores; 10054 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 10055 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 10056 DAG.getVectorIdxConstant(Idx, SL)); 10057 10058 SDValue Ptr = 10059 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride)); 10060 10061 // This scalar TruncStore may be illegal, but we legalize it later. 10062 SDValue Store = DAG.getTruncStore( 10063 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 10064 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 10065 ST->getAAInfo()); 10066 10067 Stores.push_back(Store); 10068 } 10069 10070 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 10071 } 10072 10073 std::pair<SDValue, SDValue> 10074 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 10075 assert(LD->getAddressingMode() == ISD::UNINDEXED && 10076 "unaligned indexed loads not implemented!"); 10077 SDValue Chain = LD->getChain(); 10078 SDValue Ptr = LD->getBasePtr(); 10079 EVT VT = LD->getValueType(0); 10080 EVT LoadedVT = LD->getMemoryVT(); 10081 SDLoc dl(LD); 10082 auto &MF = DAG.getMachineFunction(); 10083 10084 if (VT.isFloatingPoint() || VT.isVector()) { 10085 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 10086 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 10087 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 10088 LoadedVT.isVector()) { 10089 // Scalarize the load and let the individual components be handled. 10090 return scalarizeVectorLoad(LD, DAG); 10091 } 10092 10093 // Expand to a (misaligned) integer load of the same size, 10094 // then bitconvert to floating point or vector. 10095 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 10096 LD->getMemOperand()); 10097 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 10098 if (LoadedVT != VT) 10099 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 10100 ISD::ANY_EXTEND, dl, VT, Result); 10101 10102 return std::make_pair(Result, newLoad.getValue(1)); 10103 } 10104 10105 // Copy the value to a (aligned) stack slot using (unaligned) integer 10106 // loads and stores, then do a (aligned) load from the stack slot. 10107 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 10108 unsigned LoadedBytes = LoadedVT.getStoreSize(); 10109 unsigned RegBytes = RegVT.getSizeInBits() / 8; 10110 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 10111 10112 // Make sure the stack slot is also aligned for the register type. 10113 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 10114 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 10115 SmallVector<SDValue, 8> Stores; 10116 SDValue StackPtr = StackBase; 10117 unsigned Offset = 0; 10118 10119 EVT PtrVT = Ptr.getValueType(); 10120 EVT StackPtrVT = StackPtr.getValueType(); 10121 10122 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 10123 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 10124 10125 // Do all but one copies using the full register width. 10126 for (unsigned i = 1; i < NumRegs; i++) { 10127 // Load one integer register's worth from the original location. 10128 SDValue Load = DAG.getLoad( 10129 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 10130 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 10131 LD->getAAInfo()); 10132 // Follow the load with a store to the stack slot. Remember the store. 10133 Stores.push_back(DAG.getStore( 10134 Load.getValue(1), dl, Load, StackPtr, 10135 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 10136 // Increment the pointers. 10137 Offset += RegBytes; 10138 10139 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 10140 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 10141 } 10142 10143 // The last copy may be partial. Do an extending load. 10144 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 10145 8 * (LoadedBytes - Offset)); 10146 SDValue Load = 10147 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 10148 LD->getPointerInfo().getWithOffset(Offset), MemVT, 10149 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 10150 LD->getAAInfo()); 10151 // Follow the load with a store to the stack slot. Remember the store. 10152 // On big-endian machines this requires a truncating store to ensure 10153 // that the bits end up in the right place. 10154 Stores.push_back(DAG.getTruncStore( 10155 Load.getValue(1), dl, Load, StackPtr, 10156 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 10157 10158 // The order of the stores doesn't matter - say it with a TokenFactor. 10159 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10160 10161 // Finally, perform the original load only redirected to the stack slot. 10162 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 10163 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 10164 LoadedVT); 10165 10166 // Callers expect a MERGE_VALUES node. 10167 return std::make_pair(Load, TF); 10168 } 10169 10170 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 10171 "Unaligned load of unsupported type."); 10172 10173 // Compute the new VT that is half the size of the old one. This is an 10174 // integer MVT. 10175 unsigned NumBits = LoadedVT.getSizeInBits(); 10176 EVT NewLoadedVT; 10177 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 10178 NumBits >>= 1; 10179 10180 Align Alignment = LD->getOriginalAlign(); 10181 unsigned IncrementSize = NumBits / 8; 10182 ISD::LoadExtType HiExtType = LD->getExtensionType(); 10183 10184 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 10185 if (HiExtType == ISD::NON_EXTLOAD) 10186 HiExtType = ISD::ZEXTLOAD; 10187 10188 // Load the value in two parts 10189 SDValue Lo, Hi; 10190 if (DAG.getDataLayout().isLittleEndian()) { 10191 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 10192 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10193 LD->getAAInfo()); 10194 10195 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10196 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 10197 LD->getPointerInfo().getWithOffset(IncrementSize), 10198 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10199 LD->getAAInfo()); 10200 } else { 10201 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 10202 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10203 LD->getAAInfo()); 10204 10205 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10206 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 10207 LD->getPointerInfo().getWithOffset(IncrementSize), 10208 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10209 LD->getAAInfo()); 10210 } 10211 10212 // aggregate the two parts 10213 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl); 10214 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 10215 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 10216 10217 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 10218 Hi.getValue(1)); 10219 10220 return std::make_pair(Result, TF); 10221 } 10222 10223 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 10224 SelectionDAG &DAG) const { 10225 assert(ST->getAddressingMode() == ISD::UNINDEXED && 10226 "unaligned indexed stores not implemented!"); 10227 SDValue Chain = ST->getChain(); 10228 SDValue Ptr = ST->getBasePtr(); 10229 SDValue Val = ST->getValue(); 10230 EVT VT = Val.getValueType(); 10231 Align Alignment = ST->getOriginalAlign(); 10232 auto &MF = DAG.getMachineFunction(); 10233 EVT StoreMemVT = ST->getMemoryVT(); 10234 10235 SDLoc dl(ST); 10236 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 10237 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10238 if (isTypeLegal(intVT)) { 10239 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 10240 StoreMemVT.isVector()) { 10241 // Scalarize the store and let the individual components be handled. 10242 SDValue Result = scalarizeVectorStore(ST, DAG); 10243 return Result; 10244 } 10245 // Expand to a bitconvert of the value to the integer type of the 10246 // same size, then a (misaligned) int store. 10247 // FIXME: Does not handle truncating floating point stores! 10248 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 10249 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 10250 Alignment, ST->getMemOperand()->getFlags()); 10251 return Result; 10252 } 10253 // Do a (aligned) store to a stack slot, then copy from the stack slot 10254 // to the final destination using (unaligned) integer loads and stores. 10255 MVT RegVT = getRegisterType( 10256 *DAG.getContext(), 10257 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 10258 EVT PtrVT = Ptr.getValueType(); 10259 unsigned StoredBytes = StoreMemVT.getStoreSize(); 10260 unsigned RegBytes = RegVT.getSizeInBits() / 8; 10261 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 10262 10263 // Make sure the stack slot is also aligned for the register type. 10264 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 10265 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 10266 10267 // Perform the original store, only redirected to the stack slot. 10268 SDValue Store = DAG.getTruncStore( 10269 Chain, dl, Val, StackPtr, 10270 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 10271 10272 EVT StackPtrVT = StackPtr.getValueType(); 10273 10274 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 10275 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 10276 SmallVector<SDValue, 8> Stores; 10277 unsigned Offset = 0; 10278 10279 // Do all but one copies using the full register width. 10280 for (unsigned i = 1; i < NumRegs; i++) { 10281 // Load one integer register's worth from the stack slot. 10282 SDValue Load = DAG.getLoad( 10283 RegVT, dl, Store, StackPtr, 10284 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 10285 // Store it to the final location. Remember the store. 10286 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 10287 ST->getPointerInfo().getWithOffset(Offset), 10288 ST->getOriginalAlign(), 10289 ST->getMemOperand()->getFlags())); 10290 // Increment the pointers. 10291 Offset += RegBytes; 10292 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 10293 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 10294 } 10295 10296 // The last store may be partial. Do a truncating store. On big-endian 10297 // machines this requires an extending load from the stack slot to ensure 10298 // that the bits are in the right place. 10299 EVT LoadMemVT = 10300 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 10301 10302 // Load from the stack slot. 10303 SDValue Load = DAG.getExtLoad( 10304 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 10305 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 10306 10307 Stores.push_back( 10308 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 10309 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 10310 ST->getOriginalAlign(), 10311 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 10312 // The order of the stores doesn't matter - say it with a TokenFactor. 10313 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10314 return Result; 10315 } 10316 10317 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 10318 "Unaligned store of unknown type."); 10319 // Get the half-size VT 10320 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 10321 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 10322 unsigned IncrementSize = NumBits / 8; 10323 10324 // Divide the stored value in two parts. 10325 SDValue ShiftAmount = 10326 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl); 10327 SDValue Lo = Val; 10328 // If Val is a constant, replace the upper bits with 0. The SRL will constant 10329 // fold and not use the upper bits. A smaller constant may be easier to 10330 // materialize. 10331 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque()) 10332 Lo = DAG.getNode( 10333 ISD::AND, dl, VT, Lo, 10334 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl, 10335 VT)); 10336 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 10337 10338 // Store the two parts 10339 SDValue Store1, Store2; 10340 Store1 = DAG.getTruncStore(Chain, dl, 10341 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 10342 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 10343 ST->getMemOperand()->getFlags()); 10344 10345 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10346 Store2 = DAG.getTruncStore( 10347 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 10348 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 10349 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 10350 10351 SDValue Result = 10352 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 10353 return Result; 10354 } 10355 10356 SDValue 10357 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 10358 const SDLoc &DL, EVT DataVT, 10359 SelectionDAG &DAG, 10360 bool IsCompressedMemory) const { 10361 SDValue Increment; 10362 EVT AddrVT = Addr.getValueType(); 10363 EVT MaskVT = Mask.getValueType(); 10364 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 10365 "Incompatible types of Data and Mask"); 10366 if (IsCompressedMemory) { 10367 if (DataVT.isScalableVector()) 10368 report_fatal_error( 10369 "Cannot currently handle compressed memory with scalable vectors"); 10370 // Incrementing the pointer according to number of '1's in the mask. 10371 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 10372 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 10373 if (MaskIntVT.getSizeInBits() < 32) { 10374 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 10375 MaskIntVT = MVT::i32; 10376 } 10377 10378 // Count '1's with POPCNT. 10379 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 10380 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 10381 // Scale is an element size in bytes. 10382 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 10383 AddrVT); 10384 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 10385 } else if (DataVT.isScalableVector()) { 10386 Increment = DAG.getVScale(DL, AddrVT, 10387 APInt(AddrVT.getFixedSizeInBits(), 10388 DataVT.getStoreSize().getKnownMinValue())); 10389 } else 10390 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 10391 10392 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 10393 } 10394 10395 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 10396 EVT VecVT, const SDLoc &dl, 10397 ElementCount SubEC) { 10398 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 10399 "Cannot index a scalable vector within a fixed-width vector"); 10400 10401 unsigned NElts = VecVT.getVectorMinNumElements(); 10402 unsigned NumSubElts = SubEC.getKnownMinValue(); 10403 EVT IdxVT = Idx.getValueType(); 10404 10405 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 10406 // If this is a constant index and we know the value plus the number of the 10407 // elements in the subvector minus one is less than the minimum number of 10408 // elements then it's safe to return Idx. 10409 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 10410 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 10411 return Idx; 10412 SDValue VS = 10413 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 10414 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 10415 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 10416 DAG.getConstant(NumSubElts, dl, IdxVT)); 10417 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 10418 } 10419 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 10420 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 10421 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 10422 DAG.getConstant(Imm, dl, IdxVT)); 10423 } 10424 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 10425 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 10426 DAG.getConstant(MaxIndex, dl, IdxVT)); 10427 } 10428 10429 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 10430 SDValue VecPtr, EVT VecVT, 10431 SDValue Index) const { 10432 return getVectorSubVecPointer( 10433 DAG, VecPtr, VecVT, 10434 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 10435 Index); 10436 } 10437 10438 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 10439 SDValue VecPtr, EVT VecVT, 10440 EVT SubVecVT, 10441 SDValue Index) const { 10442 SDLoc dl(Index); 10443 // Make sure the index type is big enough to compute in. 10444 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 10445 10446 EVT EltVT = VecVT.getVectorElementType(); 10447 10448 // Calculate the element offset and add it to the pointer. 10449 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 10450 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 10451 "Converting bits to bytes lost precision"); 10452 assert(SubVecVT.getVectorElementType() == EltVT && 10453 "Sub-vector must be a vector with matching element type"); 10454 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 10455 SubVecVT.getVectorElementCount()); 10456 10457 EVT IdxVT = Index.getValueType(); 10458 if (SubVecVT.isScalableVector()) 10459 Index = 10460 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 10461 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 10462 10463 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 10464 DAG.getConstant(EltSize, dl, IdxVT)); 10465 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 10466 } 10467 10468 //===----------------------------------------------------------------------===// 10469 // Implementation of Emulated TLS Model 10470 //===----------------------------------------------------------------------===// 10471 10472 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 10473 SelectionDAG &DAG) const { 10474 // Access to address of TLS varialbe xyz is lowered to a function call: 10475 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 10476 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10477 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0); 10478 SDLoc dl(GA); 10479 10480 ArgListTy Args; 10481 ArgListEntry Entry; 10482 const GlobalValue *GV = 10483 cast<GlobalValue>(GA->getGlobal()->stripPointerCastsAndAliases()); 10484 SmallString<32> NameString("__emutls_v."); 10485 NameString += GV->getName(); 10486 StringRef EmuTlsVarName(NameString); 10487 const GlobalVariable *EmuTlsVar = 10488 GV->getParent()->getNamedGlobal(EmuTlsVarName); 10489 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 10490 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 10491 Entry.Ty = VoidPtrType; 10492 Args.push_back(Entry); 10493 10494 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 10495 10496 TargetLowering::CallLoweringInfo CLI(DAG); 10497 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 10498 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 10499 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 10500 10501 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 10502 // At last for X86 targets, maybe good for other targets too? 10503 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10504 MFI.setAdjustsStack(true); // Is this only for X86 target? 10505 MFI.setHasCalls(true); 10506 10507 assert((GA->getOffset() == 0) && 10508 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 10509 return CallResult.first; 10510 } 10511 10512 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 10513 SelectionDAG &DAG) const { 10514 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 10515 if (!isCtlzFast()) 10516 return SDValue(); 10517 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10518 SDLoc dl(Op); 10519 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) { 10520 EVT VT = Op.getOperand(0).getValueType(); 10521 SDValue Zext = Op.getOperand(0); 10522 if (VT.bitsLT(MVT::i32)) { 10523 VT = MVT::i32; 10524 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 10525 } 10526 unsigned Log2b = Log2_32(VT.getSizeInBits()); 10527 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 10528 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 10529 DAG.getConstant(Log2b, dl, MVT::i32)); 10530 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 10531 } 10532 return SDValue(); 10533 } 10534 10535 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 10536 SDValue Op0 = Node->getOperand(0); 10537 SDValue Op1 = Node->getOperand(1); 10538 EVT VT = Op0.getValueType(); 10539 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10540 unsigned Opcode = Node->getOpcode(); 10541 SDLoc DL(Node); 10542 10543 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits 10544 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT && 10545 getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10546 Op0 = DAG.getFreeze(Op0); 10547 SDValue Zero = DAG.getConstant(0, DL, VT); 10548 return DAG.getNode(ISD::SUB, DL, VT, Op0, 10549 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ)); 10550 } 10551 10552 // umin(x,y) -> sub(x,usubsat(x,y)) 10553 // TODO: Missing freeze(Op0)? 10554 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 10555 isOperationLegal(ISD::USUBSAT, VT)) { 10556 return DAG.getNode(ISD::SUB, DL, VT, Op0, 10557 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 10558 } 10559 10560 // umax(x,y) -> add(x,usubsat(y,x)) 10561 // TODO: Missing freeze(Op0)? 10562 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 10563 isOperationLegal(ISD::USUBSAT, VT)) { 10564 return DAG.getNode(ISD::ADD, DL, VT, Op0, 10565 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 10566 } 10567 10568 // FIXME: Should really try to split the vector in case it's legal on a 10569 // subvector. 10570 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10571 return DAG.UnrollVectorOp(Node); 10572 10573 // Attempt to find an existing SETCC node that we can reuse. 10574 // TODO: Do we need a generic doesSETCCNodeExist? 10575 // TODO: Missing freeze(Op0)/freeze(Op1)? 10576 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC, 10577 ISD::CondCode PrefCommuteCC, 10578 ISD::CondCode AltCommuteCC) { 10579 SDVTList BoolVTList = DAG.getVTList(BoolVT); 10580 for (ISD::CondCode CC : {PrefCC, AltCC}) { 10581 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 10582 {Op0, Op1, DAG.getCondCode(CC)})) { 10583 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 10584 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 10585 } 10586 } 10587 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) { 10588 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 10589 {Op0, Op1, DAG.getCondCode(CC)})) { 10590 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 10591 return DAG.getSelect(DL, VT, Cond, Op1, Op0); 10592 } 10593 } 10594 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC); 10595 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 10596 }; 10597 10598 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 10599 // -> Y = (A < B) ? B : A 10600 // -> Y = (A >= B) ? A : B 10601 // -> Y = (A <= B) ? B : A 10602 switch (Opcode) { 10603 case ISD::SMAX: 10604 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE); 10605 case ISD::SMIN: 10606 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE); 10607 case ISD::UMAX: 10608 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE); 10609 case ISD::UMIN: 10610 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE); 10611 } 10612 10613 llvm_unreachable("How did we get here?"); 10614 } 10615 10616 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 10617 unsigned Opcode = Node->getOpcode(); 10618 SDValue LHS = Node->getOperand(0); 10619 SDValue RHS = Node->getOperand(1); 10620 EVT VT = LHS.getValueType(); 10621 SDLoc dl(Node); 10622 10623 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10624 assert(VT.isInteger() && "Expected operands to be integers"); 10625 10626 // usub.sat(a, b) -> umax(a, b) - b 10627 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 10628 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 10629 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 10630 } 10631 10632 // uadd.sat(a, b) -> umin(a, ~b) + b 10633 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 10634 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 10635 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 10636 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 10637 } 10638 10639 unsigned OverflowOp; 10640 switch (Opcode) { 10641 case ISD::SADDSAT: 10642 OverflowOp = ISD::SADDO; 10643 break; 10644 case ISD::UADDSAT: 10645 OverflowOp = ISD::UADDO; 10646 break; 10647 case ISD::SSUBSAT: 10648 OverflowOp = ISD::SSUBO; 10649 break; 10650 case ISD::USUBSAT: 10651 OverflowOp = ISD::USUBO; 10652 break; 10653 default: 10654 llvm_unreachable("Expected method to receive signed or unsigned saturation " 10655 "addition or subtraction node."); 10656 } 10657 10658 // FIXME: Should really try to split the vector in case it's legal on a 10659 // subvector. 10660 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10661 return DAG.UnrollVectorOp(Node); 10662 10663 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 10664 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10665 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10666 SDValue SumDiff = Result.getValue(0); 10667 SDValue Overflow = Result.getValue(1); 10668 SDValue Zero = DAG.getConstant(0, dl, VT); 10669 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 10670 10671 if (Opcode == ISD::UADDSAT) { 10672 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10673 // (LHS + RHS) | OverflowMask 10674 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10675 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 10676 } 10677 // Overflow ? 0xffff.... : (LHS + RHS) 10678 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 10679 } 10680 10681 if (Opcode == ISD::USUBSAT) { 10682 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10683 // (LHS - RHS) & ~OverflowMask 10684 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10685 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 10686 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 10687 } 10688 // Overflow ? 0 : (LHS - RHS) 10689 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 10690 } 10691 10692 if (Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) { 10693 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10694 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 10695 10696 KnownBits KnownLHS = DAG.computeKnownBits(LHS); 10697 KnownBits KnownRHS = DAG.computeKnownBits(RHS); 10698 10699 // If either of the operand signs are known, then they are guaranteed to 10700 // only saturate in one direction. If non-negative they will saturate 10701 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN. 10702 // 10703 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the 10704 // sign of 'y' has to be flipped. 10705 10706 bool LHSIsNonNegative = KnownLHS.isNonNegative(); 10707 bool RHSIsNonNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() 10708 : KnownRHS.isNegative(); 10709 if (LHSIsNonNegative || RHSIsNonNegative) { 10710 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10711 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff); 10712 } 10713 10714 bool LHSIsNegative = KnownLHS.isNegative(); 10715 bool RHSIsNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNegative() 10716 : KnownRHS.isNonNegative(); 10717 if (LHSIsNegative || RHSIsNegative) { 10718 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10719 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff); 10720 } 10721 } 10722 10723 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 10724 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10725 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10726 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 10727 DAG.getConstant(BitWidth - 1, dl, VT)); 10728 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 10729 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 10730 } 10731 10732 SDValue TargetLowering::expandCMP(SDNode *Node, SelectionDAG &DAG) const { 10733 unsigned Opcode = Node->getOpcode(); 10734 SDValue LHS = Node->getOperand(0); 10735 SDValue RHS = Node->getOperand(1); 10736 EVT VT = LHS.getValueType(); 10737 EVT ResVT = Node->getValueType(0); 10738 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10739 SDLoc dl(Node); 10740 10741 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT); 10742 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT); 10743 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate); 10744 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate); 10745 10746 // We can't perform arithmetic on i1 values. Extending them would 10747 // probably result in worse codegen, so let's just use two selects instead. 10748 // Some targets are also just better off using selects rather than subtraction 10749 // because one of the conditions can be merged with one of the selects. 10750 // And finally, if we don't know the contents of high bits of a boolean value 10751 // we can't perform any arithmetic either. 10752 if (shouldExpandCmpUsingSelects(VT) || BoolVT.getScalarSizeInBits() == 1 || 10753 getBooleanContents(BoolVT) == UndefinedBooleanContent) { 10754 SDValue SelectZeroOrOne = 10755 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT), 10756 DAG.getConstant(0, dl, ResVT)); 10757 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT), 10758 SelectZeroOrOne); 10759 } 10760 10761 if (getBooleanContents(BoolVT) == ZeroOrNegativeOneBooleanContent) 10762 std::swap(IsGT, IsLT); 10763 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl, 10764 ResVT); 10765 } 10766 10767 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 10768 unsigned Opcode = Node->getOpcode(); 10769 bool IsSigned = Opcode == ISD::SSHLSAT; 10770 SDValue LHS = Node->getOperand(0); 10771 SDValue RHS = Node->getOperand(1); 10772 EVT VT = LHS.getValueType(); 10773 SDLoc dl(Node); 10774 10775 assert((Node->getOpcode() == ISD::SSHLSAT || 10776 Node->getOpcode() == ISD::USHLSAT) && 10777 "Expected a SHLSAT opcode"); 10778 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10779 assert(VT.isInteger() && "Expected operands to be integers"); 10780 10781 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10782 return DAG.UnrollVectorOp(Node); 10783 10784 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 10785 10786 unsigned BW = VT.getScalarSizeInBits(); 10787 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10788 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 10789 SDValue Orig = 10790 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 10791 10792 SDValue SatVal; 10793 if (IsSigned) { 10794 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 10795 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 10796 SDValue Cond = 10797 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT); 10798 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax); 10799 } else { 10800 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 10801 } 10802 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE); 10803 return DAG.getSelect(dl, VT, Cond, SatVal, Result); 10804 } 10805 10806 void TargetLowering::forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, 10807 bool Signed, EVT WideVT, 10808 const SDValue LL, const SDValue LH, 10809 const SDValue RL, const SDValue RH, 10810 SDValue &Lo, SDValue &Hi) const { 10811 // We can fall back to a libcall with an illegal type for the MUL if we 10812 // have a libcall big enough. 10813 // Also, we can fall back to a division in some cases, but that's a big 10814 // performance hit in the general case. 10815 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 10816 if (WideVT == MVT::i16) 10817 LC = RTLIB::MUL_I16; 10818 else if (WideVT == MVT::i32) 10819 LC = RTLIB::MUL_I32; 10820 else if (WideVT == MVT::i64) 10821 LC = RTLIB::MUL_I64; 10822 else if (WideVT == MVT::i128) 10823 LC = RTLIB::MUL_I128; 10824 10825 if (LC == RTLIB::UNKNOWN_LIBCALL || !getLibcallName(LC)) { 10826 // We'll expand the multiplication by brute force because we have no other 10827 // options. This is a trivially-generalized version of the code from 10828 // Hacker's Delight (itself derived from Knuth's Algorithm M from section 10829 // 4.3.1). 10830 EVT VT = LL.getValueType(); 10831 unsigned Bits = VT.getSizeInBits(); 10832 unsigned HalfBits = Bits >> 1; 10833 SDValue Mask = 10834 DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT); 10835 SDValue LLL = DAG.getNode(ISD::AND, dl, VT, LL, Mask); 10836 SDValue RLL = DAG.getNode(ISD::AND, dl, VT, RL, Mask); 10837 10838 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LLL, RLL); 10839 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask); 10840 10841 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl); 10842 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift); 10843 SDValue LLH = DAG.getNode(ISD::SRL, dl, VT, LL, Shift); 10844 SDValue RLH = DAG.getNode(ISD::SRL, dl, VT, RL, Shift); 10845 10846 SDValue U = DAG.getNode(ISD::ADD, dl, VT, 10847 DAG.getNode(ISD::MUL, dl, VT, LLH, RLL), TH); 10848 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask); 10849 SDValue UH = DAG.getNode(ISD::SRL, dl, VT, U, Shift); 10850 10851 SDValue V = DAG.getNode(ISD::ADD, dl, VT, 10852 DAG.getNode(ISD::MUL, dl, VT, LLL, RLH), UL); 10853 SDValue VH = DAG.getNode(ISD::SRL, dl, VT, V, Shift); 10854 10855 SDValue W = 10856 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LLH, RLH), 10857 DAG.getNode(ISD::ADD, dl, VT, UH, VH)); 10858 Lo = DAG.getNode(ISD::ADD, dl, VT, TL, 10859 DAG.getNode(ISD::SHL, dl, VT, V, Shift)); 10860 10861 Hi = DAG.getNode(ISD::ADD, dl, VT, W, 10862 DAG.getNode(ISD::ADD, dl, VT, 10863 DAG.getNode(ISD::MUL, dl, VT, RH, LL), 10864 DAG.getNode(ISD::MUL, dl, VT, RL, LH))); 10865 } else { 10866 // Attempt a libcall. 10867 SDValue Ret; 10868 TargetLowering::MakeLibCallOptions CallOptions; 10869 CallOptions.setSExt(Signed); 10870 CallOptions.setIsPostTypeLegalization(true); 10871 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 10872 // Halves of WideVT are packed into registers in different order 10873 // depending on platform endianness. This is usually handled by 10874 // the C calling convention, but we can't defer to it in 10875 // the legalizer. 10876 SDValue Args[] = {LL, LH, RL, RH}; 10877 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10878 } else { 10879 SDValue Args[] = {LH, LL, RH, RL}; 10880 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10881 } 10882 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 10883 "Ret value is a collection of constituent nodes holding result."); 10884 if (DAG.getDataLayout().isLittleEndian()) { 10885 // Same as above. 10886 Lo = Ret.getOperand(0); 10887 Hi = Ret.getOperand(1); 10888 } else { 10889 Lo = Ret.getOperand(1); 10890 Hi = Ret.getOperand(0); 10891 } 10892 } 10893 } 10894 10895 void TargetLowering::forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, 10896 bool Signed, const SDValue LHS, 10897 const SDValue RHS, SDValue &Lo, 10898 SDValue &Hi) const { 10899 EVT VT = LHS.getValueType(); 10900 assert(RHS.getValueType() == VT && "Mismatching operand types"); 10901 10902 SDValue HiLHS; 10903 SDValue HiRHS; 10904 if (Signed) { 10905 // The high part is obtained by SRA'ing all but one of the bits of low 10906 // part. 10907 unsigned LoSize = VT.getFixedSizeInBits(); 10908 HiLHS = DAG.getNode( 10909 ISD::SRA, dl, VT, LHS, 10910 DAG.getConstant(LoSize - 1, dl, getPointerTy(DAG.getDataLayout()))); 10911 HiRHS = DAG.getNode( 10912 ISD::SRA, dl, VT, RHS, 10913 DAG.getConstant(LoSize - 1, dl, getPointerTy(DAG.getDataLayout()))); 10914 } else { 10915 HiLHS = DAG.getConstant(0, dl, VT); 10916 HiRHS = DAG.getConstant(0, dl, VT); 10917 } 10918 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2); 10919 forceExpandWideMUL(DAG, dl, Signed, WideVT, LHS, HiLHS, RHS, HiRHS, Lo, Hi); 10920 } 10921 10922 SDValue 10923 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 10924 assert((Node->getOpcode() == ISD::SMULFIX || 10925 Node->getOpcode() == ISD::UMULFIX || 10926 Node->getOpcode() == ISD::SMULFIXSAT || 10927 Node->getOpcode() == ISD::UMULFIXSAT) && 10928 "Expected a fixed point multiplication opcode"); 10929 10930 SDLoc dl(Node); 10931 SDValue LHS = Node->getOperand(0); 10932 SDValue RHS = Node->getOperand(1); 10933 EVT VT = LHS.getValueType(); 10934 unsigned Scale = Node->getConstantOperandVal(2); 10935 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 10936 Node->getOpcode() == ISD::UMULFIXSAT); 10937 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 10938 Node->getOpcode() == ISD::SMULFIXSAT); 10939 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10940 unsigned VTSize = VT.getScalarSizeInBits(); 10941 10942 if (!Scale) { 10943 // [us]mul.fix(a, b, 0) -> mul(a, b) 10944 if (!Saturating) { 10945 if (isOperationLegalOrCustom(ISD::MUL, VT)) 10946 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10947 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 10948 SDValue Result = 10949 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10950 SDValue Product = Result.getValue(0); 10951 SDValue Overflow = Result.getValue(1); 10952 SDValue Zero = DAG.getConstant(0, dl, VT); 10953 10954 APInt MinVal = APInt::getSignedMinValue(VTSize); 10955 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 10956 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10957 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10958 // Xor the inputs, if resulting sign bit is 0 the product will be 10959 // positive, else negative. 10960 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 10961 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 10962 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 10963 return DAG.getSelect(dl, VT, Overflow, Result, Product); 10964 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 10965 SDValue Result = 10966 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10967 SDValue Product = Result.getValue(0); 10968 SDValue Overflow = Result.getValue(1); 10969 10970 APInt MaxVal = APInt::getMaxValue(VTSize); 10971 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10972 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 10973 } 10974 } 10975 10976 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 10977 "Expected scale to be less than the number of bits if signed or at " 10978 "most the number of bits if unsigned."); 10979 assert(LHS.getValueType() == RHS.getValueType() && 10980 "Expected both operands to be the same type"); 10981 10982 // Get the upper and lower bits of the result. 10983 SDValue Lo, Hi; 10984 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 10985 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 10986 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VTSize * 2); 10987 if (VT.isVector()) 10988 WideVT = 10989 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 10990 if (isOperationLegalOrCustom(LoHiOp, VT)) { 10991 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 10992 Lo = Result.getValue(0); 10993 Hi = Result.getValue(1); 10994 } else if (isOperationLegalOrCustom(HiOp, VT)) { 10995 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10996 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 10997 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) { 10998 // Try for a multiplication using a wider type. 10999 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 11000 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS); 11001 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS); 11002 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt); 11003 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res); 11004 SDValue Shifted = 11005 DAG.getNode(ISD::SRA, dl, WideVT, Res, 11006 DAG.getShiftAmountConstant(VTSize, WideVT, dl)); 11007 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted); 11008 } else if (VT.isVector()) { 11009 return SDValue(); 11010 } else { 11011 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi); 11012 } 11013 11014 if (Scale == VTSize) 11015 // Result is just the top half since we'd be shifting by the width of the 11016 // operand. Overflow impossible so this works for both UMULFIX and 11017 // UMULFIXSAT. 11018 return Hi; 11019 11020 // The result will need to be shifted right by the scale since both operands 11021 // are scaled. The result is given to us in 2 halves, so we only want part of 11022 // both in the result. 11023 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 11024 DAG.getShiftAmountConstant(Scale, VT, dl)); 11025 if (!Saturating) 11026 return Result; 11027 11028 if (!Signed) { 11029 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 11030 // widened multiplication) aren't all zeroes. 11031 11032 // Saturate to max if ((Hi >> Scale) != 0), 11033 // which is the same as if (Hi > ((1 << Scale) - 1)) 11034 APInt MaxVal = APInt::getMaxValue(VTSize); 11035 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 11036 dl, VT); 11037 Result = DAG.getSelectCC(dl, Hi, LowMask, 11038 DAG.getConstant(MaxVal, dl, VT), Result, 11039 ISD::SETUGT); 11040 11041 return Result; 11042 } 11043 11044 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 11045 // widened multiplication) aren't all ones or all zeroes. 11046 11047 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 11048 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 11049 11050 if (Scale == 0) { 11051 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 11052 DAG.getShiftAmountConstant(VTSize - 1, VT, dl)); 11053 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 11054 // Saturated to SatMin if wide product is negative, and SatMax if wide 11055 // product is positive ... 11056 SDValue Zero = DAG.getConstant(0, dl, VT); 11057 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 11058 ISD::SETLT); 11059 // ... but only if we overflowed. 11060 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 11061 } 11062 11063 // We handled Scale==0 above so all the bits to examine is in Hi. 11064 11065 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 11066 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 11067 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 11068 dl, VT); 11069 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 11070 // Saturate to min if (Hi >> (Scale - 1)) < -1), 11071 // which is the same as if (HI < (-1 << (Scale - 1)) 11072 SDValue HighMask = 11073 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 11074 dl, VT); 11075 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 11076 return Result; 11077 } 11078 11079 SDValue 11080 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 11081 SDValue LHS, SDValue RHS, 11082 unsigned Scale, SelectionDAG &DAG) const { 11083 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 11084 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 11085 "Expected a fixed point division opcode"); 11086 11087 EVT VT = LHS.getValueType(); 11088 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 11089 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 11090 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 11091 11092 // If there is enough room in the type to upscale the LHS or downscale the 11093 // RHS before the division, we can perform it in this type without having to 11094 // resize. For signed operations, the LHS headroom is the number of 11095 // redundant sign bits, and for unsigned ones it is the number of zeroes. 11096 // The headroom for the RHS is the number of trailing zeroes. 11097 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 11098 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 11099 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 11100 11101 // For signed saturating operations, we need to be able to detect true integer 11102 // division overflow; that is, when you have MIN / -EPS. However, this 11103 // is undefined behavior and if we emit divisions that could take such 11104 // values it may cause undesired behavior (arithmetic exceptions on x86, for 11105 // example). 11106 // Avoid this by requiring an extra bit so that we never get this case. 11107 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 11108 // signed saturating division, we need to emit a whopping 32-bit division. 11109 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 11110 return SDValue(); 11111 11112 unsigned LHSShift = std::min(LHSLead, Scale); 11113 unsigned RHSShift = Scale - LHSShift; 11114 11115 // At this point, we know that if we shift the LHS up by LHSShift and the 11116 // RHS down by RHSShift, we can emit a regular division with a final scaling 11117 // factor of Scale. 11118 11119 if (LHSShift) 11120 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 11121 DAG.getShiftAmountConstant(LHSShift, VT, dl)); 11122 if (RHSShift) 11123 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 11124 DAG.getShiftAmountConstant(RHSShift, VT, dl)); 11125 11126 SDValue Quot; 11127 if (Signed) { 11128 // For signed operations, if the resulting quotient is negative and the 11129 // remainder is nonzero, subtract 1 from the quotient to round towards 11130 // negative infinity. 11131 SDValue Rem; 11132 // FIXME: Ideally we would always produce an SDIVREM here, but if the 11133 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 11134 // we couldn't just form a libcall, but the type legalizer doesn't do it. 11135 if (isTypeLegal(VT) && 11136 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 11137 Quot = DAG.getNode(ISD::SDIVREM, dl, 11138 DAG.getVTList(VT, VT), 11139 LHS, RHS); 11140 Rem = Quot.getValue(1); 11141 Quot = Quot.getValue(0); 11142 } else { 11143 Quot = DAG.getNode(ISD::SDIV, dl, VT, 11144 LHS, RHS); 11145 Rem = DAG.getNode(ISD::SREM, dl, VT, 11146 LHS, RHS); 11147 } 11148 SDValue Zero = DAG.getConstant(0, dl, VT); 11149 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 11150 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 11151 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 11152 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 11153 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 11154 DAG.getConstant(1, dl, VT)); 11155 Quot = DAG.getSelect(dl, VT, 11156 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 11157 Sub1, Quot); 11158 } else 11159 Quot = DAG.getNode(ISD::UDIV, dl, VT, 11160 LHS, RHS); 11161 11162 return Quot; 11163 } 11164 11165 void TargetLowering::expandUADDSUBO( 11166 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 11167 SDLoc dl(Node); 11168 SDValue LHS = Node->getOperand(0); 11169 SDValue RHS = Node->getOperand(1); 11170 bool IsAdd = Node->getOpcode() == ISD::UADDO; 11171 11172 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead. 11173 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY; 11174 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 11175 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 11176 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 11177 { LHS, RHS, CarryIn }); 11178 Result = SDValue(NodeCarry.getNode(), 0); 11179 Overflow = SDValue(NodeCarry.getNode(), 1); 11180 return; 11181 } 11182 11183 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 11184 LHS.getValueType(), LHS, RHS); 11185 11186 EVT ResultType = Node->getValueType(1); 11187 EVT SetCCType = getSetCCResultType( 11188 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 11189 SDValue SetCC; 11190 if (IsAdd && isOneConstant(RHS)) { 11191 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 11192 // the live range of X. We assume comparing with 0 is cheap. 11193 // The general case (X + C) < C is not necessarily beneficial. Although we 11194 // reduce the live range of X, we may introduce the materialization of 11195 // constant C. 11196 SetCC = 11197 DAG.getSetCC(dl, SetCCType, Result, 11198 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 11199 } else if (IsAdd && isAllOnesConstant(RHS)) { 11200 // Special case: uaddo X, -1 overflows if X != 0. 11201 SetCC = 11202 DAG.getSetCC(dl, SetCCType, LHS, 11203 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE); 11204 } else { 11205 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 11206 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 11207 } 11208 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 11209 } 11210 11211 void TargetLowering::expandSADDSUBO( 11212 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 11213 SDLoc dl(Node); 11214 SDValue LHS = Node->getOperand(0); 11215 SDValue RHS = Node->getOperand(1); 11216 bool IsAdd = Node->getOpcode() == ISD::SADDO; 11217 11218 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 11219 LHS.getValueType(), LHS, RHS); 11220 11221 EVT ResultType = Node->getValueType(1); 11222 EVT OType = getSetCCResultType( 11223 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 11224 11225 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 11226 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 11227 if (isOperationLegal(OpcSat, LHS.getValueType())) { 11228 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 11229 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 11230 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 11231 return; 11232 } 11233 11234 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 11235 11236 // For an addition, the result should be less than one of the operands (LHS) 11237 // if and only if the other operand (RHS) is negative, otherwise there will 11238 // be overflow. 11239 // For a subtraction, the result should be less than one of the operands 11240 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 11241 // otherwise there will be overflow. 11242 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 11243 SDValue ConditionRHS = 11244 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 11245 11246 Overflow = DAG.getBoolExtOrTrunc( 11247 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 11248 ResultType, ResultType); 11249 } 11250 11251 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 11252 SDValue &Overflow, SelectionDAG &DAG) const { 11253 SDLoc dl(Node); 11254 EVT VT = Node->getValueType(0); 11255 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 11256 SDValue LHS = Node->getOperand(0); 11257 SDValue RHS = Node->getOperand(1); 11258 bool isSigned = Node->getOpcode() == ISD::SMULO; 11259 11260 // For power-of-two multiplications we can use a simpler shift expansion. 11261 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 11262 const APInt &C = RHSC->getAPIntValue(); 11263 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 11264 if (C.isPowerOf2()) { 11265 // smulo(x, signed_min) is same as umulo(x, signed_min). 11266 bool UseArithShift = isSigned && !C.isMinSignedValue(); 11267 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl); 11268 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 11269 Overflow = DAG.getSetCC(dl, SetCCVT, 11270 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 11271 dl, VT, Result, ShiftAmt), 11272 LHS, ISD::SETNE); 11273 return true; 11274 } 11275 } 11276 11277 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 11278 if (VT.isVector()) 11279 WideVT = 11280 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 11281 11282 SDValue BottomHalf; 11283 SDValue TopHalf; 11284 static const unsigned Ops[2][3] = 11285 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 11286 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 11287 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 11288 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 11289 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 11290 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 11291 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 11292 RHS); 11293 TopHalf = BottomHalf.getValue(1); 11294 } else if (isTypeLegal(WideVT)) { 11295 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 11296 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 11297 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 11298 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 11299 SDValue ShiftAmt = 11300 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl); 11301 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 11302 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 11303 } else { 11304 if (VT.isVector()) 11305 return false; 11306 11307 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf); 11308 } 11309 11310 Result = BottomHalf; 11311 if (isSigned) { 11312 SDValue ShiftAmt = DAG.getShiftAmountConstant( 11313 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl); 11314 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 11315 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 11316 } else { 11317 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 11318 DAG.getConstant(0, dl, VT), ISD::SETNE); 11319 } 11320 11321 // Truncate the result if SetCC returns a larger type than needed. 11322 EVT RType = Node->getValueType(1); 11323 if (RType.bitsLT(Overflow.getValueType())) 11324 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 11325 11326 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 11327 "Unexpected result type for S/UMULO legalization"); 11328 return true; 11329 } 11330 11331 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 11332 SDLoc dl(Node); 11333 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 11334 SDValue Op = Node->getOperand(0); 11335 EVT VT = Op.getValueType(); 11336 11337 if (VT.isScalableVector()) 11338 report_fatal_error( 11339 "Expanding reductions for scalable vectors is undefined."); 11340 11341 // Try to use a shuffle reduction for power of two vectors. 11342 if (VT.isPow2VectorType()) { 11343 while (VT.getVectorNumElements() > 1) { 11344 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 11345 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 11346 break; 11347 11348 SDValue Lo, Hi; 11349 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 11350 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Node->getFlags()); 11351 VT = HalfVT; 11352 } 11353 } 11354 11355 EVT EltVT = VT.getVectorElementType(); 11356 unsigned NumElts = VT.getVectorNumElements(); 11357 11358 SmallVector<SDValue, 8> Ops; 11359 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 11360 11361 SDValue Res = Ops[0]; 11362 for (unsigned i = 1; i < NumElts; i++) 11363 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 11364 11365 // Result type may be wider than element type. 11366 if (EltVT != Node->getValueType(0)) 11367 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 11368 return Res; 11369 } 11370 11371 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 11372 SDLoc dl(Node); 11373 SDValue AccOp = Node->getOperand(0); 11374 SDValue VecOp = Node->getOperand(1); 11375 SDNodeFlags Flags = Node->getFlags(); 11376 11377 EVT VT = VecOp.getValueType(); 11378 EVT EltVT = VT.getVectorElementType(); 11379 11380 if (VT.isScalableVector()) 11381 report_fatal_error( 11382 "Expanding reductions for scalable vectors is undefined."); 11383 11384 unsigned NumElts = VT.getVectorNumElements(); 11385 11386 SmallVector<SDValue, 8> Ops; 11387 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 11388 11389 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 11390 11391 SDValue Res = AccOp; 11392 for (unsigned i = 0; i < NumElts; i++) 11393 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 11394 11395 return Res; 11396 } 11397 11398 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 11399 SelectionDAG &DAG) const { 11400 EVT VT = Node->getValueType(0); 11401 SDLoc dl(Node); 11402 bool isSigned = Node->getOpcode() == ISD::SREM; 11403 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 11404 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 11405 SDValue Dividend = Node->getOperand(0); 11406 SDValue Divisor = Node->getOperand(1); 11407 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 11408 SDVTList VTs = DAG.getVTList(VT, VT); 11409 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 11410 return true; 11411 } 11412 if (isOperationLegalOrCustom(DivOpc, VT)) { 11413 // X % Y -> X-X/Y*Y 11414 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 11415 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 11416 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 11417 return true; 11418 } 11419 return false; 11420 } 11421 11422 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 11423 SelectionDAG &DAG) const { 11424 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 11425 SDLoc dl(SDValue(Node, 0)); 11426 SDValue Src = Node->getOperand(0); 11427 11428 // DstVT is the result type, while SatVT is the size to which we saturate 11429 EVT SrcVT = Src.getValueType(); 11430 EVT DstVT = Node->getValueType(0); 11431 11432 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 11433 unsigned SatWidth = SatVT.getScalarSizeInBits(); 11434 unsigned DstWidth = DstVT.getScalarSizeInBits(); 11435 assert(SatWidth <= DstWidth && 11436 "Expected saturation width smaller than result width"); 11437 11438 // Determine minimum and maximum integer values and their corresponding 11439 // floating-point values. 11440 APInt MinInt, MaxInt; 11441 if (IsSigned) { 11442 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 11443 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 11444 } else { 11445 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 11446 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 11447 } 11448 11449 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as 11450 // libcall emission cannot handle this. Large result types will fail. 11451 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) { 11452 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 11453 SrcVT = Src.getValueType(); 11454 } 11455 11456 const fltSemantics &Sem = SrcVT.getFltSemantics(); 11457 APFloat MinFloat(Sem); 11458 APFloat MaxFloat(Sem); 11459 11460 APFloat::opStatus MinStatus = 11461 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 11462 APFloat::opStatus MaxStatus = 11463 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 11464 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 11465 !(MaxStatus & APFloat::opStatus::opInexact); 11466 11467 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 11468 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 11469 11470 // If the integer bounds are exactly representable as floats and min/max are 11471 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 11472 // of comparisons and selects. 11473 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 11474 isOperationLegal(ISD::FMAXNUM, SrcVT); 11475 if (AreExactFloatBounds && MinMaxLegal) { 11476 SDValue Clamped = Src; 11477 11478 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 11479 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 11480 // Clamp by MaxFloat from above. NaN cannot occur. 11481 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 11482 // Convert clamped value to integer. 11483 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 11484 dl, DstVT, Clamped); 11485 11486 // In the unsigned case we're done, because we mapped NaN to MinFloat, 11487 // which will cast to zero. 11488 if (!IsSigned) 11489 return FpToInt; 11490 11491 // Otherwise, select 0 if Src is NaN. 11492 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 11493 EVT SetCCVT = 11494 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 11495 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 11496 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt); 11497 } 11498 11499 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 11500 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 11501 11502 // Result of direct conversion. The assumption here is that the operation is 11503 // non-trapping and it's fine to apply it to an out-of-range value if we 11504 // select it away later. 11505 SDValue FpToInt = 11506 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 11507 11508 SDValue Select = FpToInt; 11509 11510 EVT SetCCVT = 11511 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 11512 11513 // If Src ULT MinFloat, select MinInt. In particular, this also selects 11514 // MinInt if Src is NaN. 11515 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT); 11516 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select); 11517 // If Src OGT MaxFloat, select MaxInt. 11518 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT); 11519 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select); 11520 11521 // In the unsigned case we are done, because we mapped NaN to MinInt, which 11522 // is already zero. 11523 if (!IsSigned) 11524 return Select; 11525 11526 // Otherwise, select 0 if Src is NaN. 11527 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 11528 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 11529 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select); 11530 } 11531 11532 SDValue TargetLowering::expandRoundInexactToOdd(EVT ResultVT, SDValue Op, 11533 const SDLoc &dl, 11534 SelectionDAG &DAG) const { 11535 EVT OperandVT = Op.getValueType(); 11536 if (OperandVT.getScalarType() == ResultVT.getScalarType()) 11537 return Op; 11538 EVT ResultIntVT = ResultVT.changeTypeToInteger(); 11539 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This 11540 // can induce double-rounding which may alter the results. We can 11541 // correct for this using a trick explained in: Boldo, Sylvie, and 11542 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS 11543 // World Congress. 2005. 11544 unsigned BitSize = OperandVT.getScalarSizeInBits(); 11545 EVT WideIntVT = OperandVT.changeTypeToInteger(); 11546 SDValue OpAsInt = DAG.getBitcast(WideIntVT, Op); 11547 SDValue SignBit = 11548 DAG.getNode(ISD::AND, dl, WideIntVT, OpAsInt, 11549 DAG.getConstant(APInt::getSignMask(BitSize), dl, WideIntVT)); 11550 SDValue AbsWide; 11551 if (isOperationLegalOrCustom(ISD::FABS, OperandVT)) { 11552 AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op); 11553 } else { 11554 SDValue ClearedSign = DAG.getNode( 11555 ISD::AND, dl, WideIntVT, OpAsInt, 11556 DAG.getConstant(APInt::getSignedMaxValue(BitSize), dl, WideIntVT)); 11557 AbsWide = DAG.getBitcast(OperandVT, ClearedSign); 11558 } 11559 SDValue AbsNarrow = DAG.getFPExtendOrRound(AbsWide, dl, ResultVT); 11560 SDValue AbsNarrowAsWide = DAG.getFPExtendOrRound(AbsNarrow, dl, OperandVT); 11561 11562 // We can keep the narrow value as-is if narrowing was exact (no 11563 // rounding error), the wide value was NaN (the narrow value is also 11564 // NaN and should be preserved) or if we rounded to the odd value. 11565 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, AbsNarrow); 11566 SDValue One = DAG.getConstant(1, dl, ResultIntVT); 11567 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT); 11568 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One); 11569 EVT ResultIntVTCCVT = getSetCCResultType( 11570 DAG.getDataLayout(), *DAG.getContext(), And.getValueType()); 11571 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT); 11572 // The result is already odd so we don't need to do anything. 11573 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE); 11574 11575 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11576 AbsWide.getValueType()); 11577 // We keep results which are exact, odd or NaN. 11578 SDValue KeepNarrow = 11579 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETUEQ); 11580 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd); 11581 // We morally performed a round-down if AbsNarrow is smaller than 11582 // AbsWide. 11583 SDValue NarrowIsRd = 11584 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT); 11585 // If the narrow value is odd or exact, pick it. 11586 // Otherwise, narrow is even and corresponds to either the rounded-up 11587 // or rounded-down value. If narrow is the rounded-down value, we want 11588 // the rounded-up value as it will be odd. 11589 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne); 11590 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust); 11591 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted); 11592 int ShiftAmount = BitSize - ResultVT.getScalarSizeInBits(); 11593 SDValue ShiftCnst = DAG.getShiftAmountConstant(ShiftAmount, WideIntVT, dl); 11594 SignBit = DAG.getNode(ISD::SRL, dl, WideIntVT, SignBit, ShiftCnst); 11595 SignBit = DAG.getNode(ISD::TRUNCATE, dl, ResultIntVT, SignBit); 11596 Op = DAG.getNode(ISD::OR, dl, ResultIntVT, Op, SignBit); 11597 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op); 11598 } 11599 11600 SDValue TargetLowering::expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const { 11601 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!"); 11602 SDValue Op = Node->getOperand(0); 11603 EVT VT = Node->getValueType(0); 11604 SDLoc dl(Node); 11605 if (VT.getScalarType() == MVT::bf16) { 11606 if (Node->getConstantOperandVal(1) == 1) { 11607 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0)); 11608 } 11609 EVT OperandVT = Op.getValueType(); 11610 SDValue IsNaN = DAG.getSetCC( 11611 dl, 11612 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT), 11613 Op, Op, ISD::SETUO); 11614 11615 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This 11616 // can induce double-rounding which may alter the results. We can 11617 // correct for this using a trick explained in: Boldo, Sylvie, and 11618 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS 11619 // World Congress. 2005. 11620 EVT F32 = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32; 11621 EVT I32 = F32.changeTypeToInteger(); 11622 Op = expandRoundInexactToOdd(F32, Op, dl, DAG); 11623 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op); 11624 11625 // Conversions should set NaN's quiet bit. This also prevents NaNs from 11626 // turning into infinities. 11627 SDValue NaN = 11628 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32)); 11629 11630 // Factor in the contribution of the low 16 bits. 11631 SDValue One = DAG.getConstant(1, dl, I32); 11632 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op, 11633 DAG.getShiftAmountConstant(16, I32, dl)); 11634 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One); 11635 SDValue RoundingBias = 11636 DAG.getNode(ISD::ADD, dl, I32, DAG.getConstant(0x7fff, dl, I32), Lsb); 11637 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias); 11638 11639 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into 11640 // 0x80000000. 11641 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add); 11642 11643 // Now that we have rounded, shift the bits into position. 11644 Op = DAG.getNode(ISD::SRL, dl, I32, Op, 11645 DAG.getShiftAmountConstant(16, I32, dl)); 11646 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op); 11647 EVT I16 = I32.isVector() ? I32.changeVectorElementType(MVT::i16) : MVT::i16; 11648 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op); 11649 return DAG.getNode(ISD::BITCAST, dl, VT, Op); 11650 } 11651 return SDValue(); 11652 } 11653 11654 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 11655 SelectionDAG &DAG) const { 11656 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 11657 assert(Node->getValueType(0).isScalableVector() && 11658 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 11659 11660 EVT VT = Node->getValueType(0); 11661 SDValue V1 = Node->getOperand(0); 11662 SDValue V2 = Node->getOperand(1); 11663 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 11664 SDLoc DL(Node); 11665 11666 // Expand through memory thusly: 11667 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 11668 // Store V1, Ptr 11669 // Store V2, Ptr + sizeof(V1) 11670 // If (Imm < 0) 11671 // TrailingElts = -Imm 11672 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 11673 // else 11674 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 11675 // Res = Load Ptr 11676 11677 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 11678 11679 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 11680 VT.getVectorElementCount() * 2); 11681 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 11682 EVT PtrVT = StackPtr.getValueType(); 11683 auto &MF = DAG.getMachineFunction(); 11684 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 11685 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 11686 11687 // Store the lo part of CONCAT_VECTORS(V1, V2) 11688 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 11689 // Store the hi part of CONCAT_VECTORS(V1, V2) 11690 SDValue OffsetToV2 = DAG.getVScale( 11691 DL, PtrVT, 11692 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinValue())); 11693 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 11694 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 11695 11696 if (Imm >= 0) { 11697 // Load back the required element. getVectorElementPointer takes care of 11698 // clamping the index if it's out-of-bounds. 11699 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 11700 // Load the spliced result 11701 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 11702 MachinePointerInfo::getUnknownStack(MF)); 11703 } 11704 11705 uint64_t TrailingElts = -Imm; 11706 11707 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 11708 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 11709 SDValue TrailingBytes = 11710 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 11711 11712 if (TrailingElts > VT.getVectorMinNumElements()) { 11713 SDValue VLBytes = 11714 DAG.getVScale(DL, PtrVT, 11715 APInt(PtrVT.getFixedSizeInBits(), 11716 VT.getStoreSize().getKnownMinValue())); 11717 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 11718 } 11719 11720 // Calculate the start address of the spliced result. 11721 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 11722 11723 // Load the spliced result 11724 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 11725 MachinePointerInfo::getUnknownStack(MF)); 11726 } 11727 11728 SDValue TargetLowering::expandVECTOR_COMPRESS(SDNode *Node, 11729 SelectionDAG &DAG) const { 11730 SDLoc DL(Node); 11731 SDValue Vec = Node->getOperand(0); 11732 SDValue Mask = Node->getOperand(1); 11733 SDValue Passthru = Node->getOperand(2); 11734 11735 EVT VecVT = Vec.getValueType(); 11736 EVT ScalarVT = VecVT.getScalarType(); 11737 EVT MaskVT = Mask.getValueType(); 11738 EVT MaskScalarVT = MaskVT.getScalarType(); 11739 11740 // Needs to be handled by targets that have scalable vector types. 11741 if (VecVT.isScalableVector()) 11742 report_fatal_error("Cannot expand masked_compress for scalable vectors."); 11743 11744 SDValue StackPtr = DAG.CreateStackTemporary( 11745 VecVT.getStoreSize(), DAG.getReducedAlign(VecVT, /*UseABI=*/false)); 11746 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 11747 MachinePointerInfo PtrInfo = 11748 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 11749 11750 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout()); 11751 SDValue Chain = DAG.getEntryNode(); 11752 SDValue OutPos = DAG.getConstant(0, DL, PositionVT); 11753 11754 bool HasPassthru = !Passthru.isUndef(); 11755 11756 // If we have a passthru vector, store it on the stack, overwrite the matching 11757 // positions and then re-write the last element that was potentially 11758 // overwritten even though mask[i] = false. 11759 if (HasPassthru) 11760 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo); 11761 11762 SDValue LastWriteVal; 11763 APInt PassthruSplatVal; 11764 bool IsSplatPassthru = 11765 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal); 11766 11767 if (IsSplatPassthru) { 11768 // As we do not know which position we wrote to last, we cannot simply 11769 // access that index from the passthru vector. So we first check if passthru 11770 // is a splat vector, to use any element ... 11771 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT); 11772 } else if (HasPassthru) { 11773 // ... if it is not a splat vector, we need to get the passthru value at 11774 // position = popcount(mask) and re-load it from the stack before it is 11775 // overwritten in the loop below. 11776 EVT PopcountVT = ScalarVT.changeTypeToInteger(); 11777 SDValue Popcount = DAG.getNode( 11778 ISD::TRUNCATE, DL, MaskVT.changeVectorElementType(MVT::i1), Mask); 11779 Popcount = 11780 DAG.getNode(ISD::ZERO_EXTEND, DL, 11781 MaskVT.changeVectorElementType(PopcountVT), Popcount); 11782 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount); 11783 SDValue LastElmtPtr = 11784 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount); 11785 LastWriteVal = DAG.getLoad( 11786 ScalarVT, DL, Chain, LastElmtPtr, 11787 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11788 Chain = LastWriteVal.getValue(1); 11789 } 11790 11791 unsigned NumElms = VecVT.getVectorNumElements(); 11792 for (unsigned I = 0; I < NumElms; I++) { 11793 SDValue Idx = DAG.getVectorIdxConstant(I, DL); 11794 11795 SDValue ValI = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Vec, Idx); 11796 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos); 11797 Chain = DAG.getStore( 11798 Chain, DL, ValI, OutPtr, 11799 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11800 11801 // Get the mask value and add it to the current output position. This 11802 // either increments by 1 if MaskI is true or adds 0 otherwise. 11803 // Freeze in case we have poison/undef mask entries. 11804 SDValue MaskI = DAG.getFreeze( 11805 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskScalarVT, Mask, Idx)); 11806 MaskI = DAG.getFreeze(MaskI); 11807 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI); 11808 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI); 11809 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI); 11810 11811 if (HasPassthru && I == NumElms - 1) { 11812 SDValue EndOfVector = 11813 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT); 11814 SDValue AllLanesSelected = 11815 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT); 11816 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector); 11817 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos); 11818 11819 // Re-write the last ValI if all lanes were selected. Otherwise, 11820 // overwrite the last write it with the passthru value. 11821 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI, 11822 LastWriteVal, SDNodeFlags::Unpredictable); 11823 Chain = DAG.getStore( 11824 Chain, DL, LastWriteVal, OutPtr, 11825 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11826 } 11827 } 11828 11829 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo); 11830 } 11831 11832 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 11833 SDValue &LHS, SDValue &RHS, 11834 SDValue &CC, SDValue Mask, 11835 SDValue EVL, bool &NeedInvert, 11836 const SDLoc &dl, SDValue &Chain, 11837 bool IsSignaling) const { 11838 MVT OpVT = LHS.getSimpleValueType(); 11839 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 11840 NeedInvert = false; 11841 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 11842 bool IsNonVP = !EVL; 11843 switch (getCondCodeAction(CCCode, OpVT)) { 11844 default: 11845 llvm_unreachable("Unknown condition code action!"); 11846 case TargetLowering::Legal: 11847 // Nothing to do. 11848 break; 11849 case TargetLowering::Expand: { 11850 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 11851 if (isCondCodeLegalOrCustom(InvCC, OpVT)) { 11852 std::swap(LHS, RHS); 11853 CC = DAG.getCondCode(InvCC); 11854 return true; 11855 } 11856 // Swapping operands didn't work. Try inverting the condition. 11857 bool NeedSwap = false; 11858 InvCC = getSetCCInverse(CCCode, OpVT); 11859 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) { 11860 // If inverting the condition is not enough, try swapping operands 11861 // on top of it. 11862 InvCC = ISD::getSetCCSwappedOperands(InvCC); 11863 NeedSwap = true; 11864 } 11865 if (isCondCodeLegalOrCustom(InvCC, OpVT)) { 11866 CC = DAG.getCondCode(InvCC); 11867 NeedInvert = true; 11868 if (NeedSwap) 11869 std::swap(LHS, RHS); 11870 return true; 11871 } 11872 11873 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 11874 unsigned Opc = 0; 11875 switch (CCCode) { 11876 default: 11877 llvm_unreachable("Don't know how to expand this condition!"); 11878 case ISD::SETUO: 11879 if (isCondCodeLegal(ISD::SETUNE, OpVT)) { 11880 CC1 = ISD::SETUNE; 11881 CC2 = ISD::SETUNE; 11882 Opc = ISD::OR; 11883 break; 11884 } 11885 assert(isCondCodeLegal(ISD::SETOEQ, OpVT) && 11886 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 11887 NeedInvert = true; 11888 [[fallthrough]]; 11889 case ISD::SETO: 11890 assert(isCondCodeLegal(ISD::SETOEQ, OpVT) && 11891 "If SETO is expanded, SETOEQ must be legal!"); 11892 CC1 = ISD::SETOEQ; 11893 CC2 = ISD::SETOEQ; 11894 Opc = ISD::AND; 11895 break; 11896 case ISD::SETONE: 11897 case ISD::SETUEQ: 11898 // If the SETUO or SETO CC isn't legal, we might be able to use 11899 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 11900 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 11901 // the operands. 11902 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 11903 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) || 11904 isCondCodeLegal(ISD::SETOLT, OpVT))) { 11905 CC1 = ISD::SETOGT; 11906 CC2 = ISD::SETOLT; 11907 Opc = ISD::OR; 11908 NeedInvert = ((unsigned)CCCode & 0x8U); 11909 break; 11910 } 11911 [[fallthrough]]; 11912 case ISD::SETOEQ: 11913 case ISD::SETOGT: 11914 case ISD::SETOGE: 11915 case ISD::SETOLT: 11916 case ISD::SETOLE: 11917 case ISD::SETUNE: 11918 case ISD::SETUGT: 11919 case ISD::SETUGE: 11920 case ISD::SETULT: 11921 case ISD::SETULE: 11922 // If we are floating point, assign and break, otherwise fall through. 11923 if (!OpVT.isInteger()) { 11924 // We can use the 4th bit to tell if we are the unordered 11925 // or ordered version of the opcode. 11926 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 11927 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 11928 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 11929 break; 11930 } 11931 // Fallthrough if we are unsigned integer. 11932 [[fallthrough]]; 11933 case ISD::SETLE: 11934 case ISD::SETGT: 11935 case ISD::SETGE: 11936 case ISD::SETLT: 11937 case ISD::SETNE: 11938 case ISD::SETEQ: 11939 // If all combinations of inverting the condition and swapping operands 11940 // didn't work then we have no means to expand the condition. 11941 llvm_unreachable("Don't know how to expand this condition!"); 11942 } 11943 11944 SDValue SetCC1, SetCC2; 11945 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 11946 // If we aren't the ordered or unorder operation, 11947 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 11948 if (IsNonVP) { 11949 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 11950 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 11951 } else { 11952 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 11953 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 11954 } 11955 } else { 11956 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 11957 if (IsNonVP) { 11958 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 11959 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 11960 } else { 11961 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 11962 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 11963 } 11964 } 11965 if (Chain) 11966 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 11967 SetCC2.getValue(1)); 11968 if (IsNonVP) 11969 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 11970 else { 11971 // Transform the binary opcode to the VP equivalent. 11972 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 11973 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 11974 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 11975 } 11976 RHS = SDValue(); 11977 CC = SDValue(); 11978 return true; 11979 } 11980 } 11981 return false; 11982 } 11983 11984 SDValue TargetLowering::expandVectorNaryOpBySplitting(SDNode *Node, 11985 SelectionDAG &DAG) const { 11986 EVT VT = Node->getValueType(0); 11987 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be 11988 // split into two equal parts. 11989 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2)) 11990 return SDValue(); 11991 11992 // Restrict expansion to cases where both parts can be concatenated. 11993 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT); 11994 if (LoVT != HiVT || !isTypeLegal(LoVT)) 11995 return SDValue(); 11996 11997 SDLoc DL(Node); 11998 unsigned Opcode = Node->getOpcode(); 11999 12000 // Don't expand if the result is likely to be unrolled anyway. 12001 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT)) 12002 return SDValue(); 12003 12004 SmallVector<SDValue, 4> LoOps, HiOps; 12005 for (const SDValue &V : Node->op_values()) { 12006 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT); 12007 LoOps.push_back(Lo); 12008 HiOps.push_back(Hi); 12009 } 12010 12011 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps); 12012 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps); 12013 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi); 12014 } 12015