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 SDValue X = DAG.getNode( 608 Op.getOpcode(), dl, SmallVT, 609 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 610 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 611 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 612 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X); 613 return TLO.CombineTo(Op, Z); 614 } 615 } 616 return false; 617 } 618 619 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 620 DAGCombinerInfo &DCI) const { 621 SelectionDAG &DAG = DCI.DAG; 622 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 623 !DCI.isBeforeLegalizeOps()); 624 KnownBits Known; 625 626 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 627 if (Simplified) { 628 DCI.AddToWorklist(Op.getNode()); 629 DCI.CommitTargetLoweringOpt(TLO); 630 } 631 return Simplified; 632 } 633 634 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 635 const APInt &DemandedElts, 636 DAGCombinerInfo &DCI) const { 637 SelectionDAG &DAG = DCI.DAG; 638 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 639 !DCI.isBeforeLegalizeOps()); 640 KnownBits Known; 641 642 bool Simplified = 643 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 644 if (Simplified) { 645 DCI.AddToWorklist(Op.getNode()); 646 DCI.CommitTargetLoweringOpt(TLO); 647 } 648 return Simplified; 649 } 650 651 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 652 KnownBits &Known, 653 TargetLoweringOpt &TLO, 654 unsigned Depth, 655 bool AssumeSingleUse) const { 656 EVT VT = Op.getValueType(); 657 658 // Since the number of lanes in a scalable vector is unknown at compile time, 659 // we track one bit which is implicitly broadcast to all lanes. This means 660 // that all lanes in a scalable vector are considered demanded. 661 APInt DemandedElts = VT.isFixedLengthVector() 662 ? APInt::getAllOnes(VT.getVectorNumElements()) 663 : APInt(1, 1); 664 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 665 AssumeSingleUse); 666 } 667 668 // TODO: Under what circumstances can we create nodes? Constant folding? 669 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 670 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 671 SelectionDAG &DAG, unsigned Depth) const { 672 EVT VT = Op.getValueType(); 673 674 // Limit search depth. 675 if (Depth >= SelectionDAG::MaxRecursionDepth) 676 return SDValue(); 677 678 // Ignore UNDEFs. 679 if (Op.isUndef()) 680 return SDValue(); 681 682 // Not demanding any bits/elts from Op. 683 if (DemandedBits == 0 || DemandedElts == 0) 684 return DAG.getUNDEF(VT); 685 686 bool IsLE = DAG.getDataLayout().isLittleEndian(); 687 unsigned NumElts = DemandedElts.getBitWidth(); 688 unsigned BitWidth = DemandedBits.getBitWidth(); 689 KnownBits LHSKnown, RHSKnown; 690 switch (Op.getOpcode()) { 691 case ISD::BITCAST: { 692 if (VT.isScalableVector()) 693 return SDValue(); 694 695 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 696 EVT SrcVT = Src.getValueType(); 697 EVT DstVT = Op.getValueType(); 698 if (SrcVT == DstVT) 699 return Src; 700 701 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 702 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 703 if (NumSrcEltBits == NumDstEltBits) 704 if (SDValue V = SimplifyMultipleUseDemandedBits( 705 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 706 return DAG.getBitcast(DstVT, V); 707 708 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 709 unsigned Scale = NumDstEltBits / NumSrcEltBits; 710 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 711 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 712 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 713 for (unsigned i = 0; i != Scale; ++i) { 714 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 715 unsigned BitOffset = EltOffset * NumSrcEltBits; 716 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 717 if (!Sub.isZero()) { 718 DemandedSrcBits |= Sub; 719 for (unsigned j = 0; j != NumElts; ++j) 720 if (DemandedElts[j]) 721 DemandedSrcElts.setBit((j * Scale) + i); 722 } 723 } 724 725 if (SDValue V = SimplifyMultipleUseDemandedBits( 726 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 727 return DAG.getBitcast(DstVT, V); 728 } 729 730 // TODO - bigendian once we have test coverage. 731 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 732 unsigned Scale = NumSrcEltBits / NumDstEltBits; 733 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 734 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 735 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 736 for (unsigned i = 0; i != NumElts; ++i) 737 if (DemandedElts[i]) { 738 unsigned Offset = (i % Scale) * NumDstEltBits; 739 DemandedSrcBits.insertBits(DemandedBits, Offset); 740 DemandedSrcElts.setBit(i / Scale); 741 } 742 743 if (SDValue V = SimplifyMultipleUseDemandedBits( 744 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 745 return DAG.getBitcast(DstVT, V); 746 } 747 748 break; 749 } 750 case ISD::FREEZE: { 751 SDValue N0 = Op.getOperand(0); 752 if (DAG.isGuaranteedNotToBeUndefOrPoison(N0, DemandedElts, 753 /*PoisonOnly=*/false)) 754 return N0; 755 break; 756 } 757 case ISD::AND: { 758 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 759 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 760 761 // If all of the demanded bits are known 1 on one side, return the other. 762 // These bits cannot contribute to the result of the 'and' in this 763 // context. 764 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 765 return Op.getOperand(0); 766 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 767 return Op.getOperand(1); 768 break; 769 } 770 case ISD::OR: { 771 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 772 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 773 774 // If all of the demanded bits are known zero on one side, return the 775 // other. These bits cannot contribute to the result of the 'or' in this 776 // context. 777 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 778 return Op.getOperand(0); 779 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 780 return Op.getOperand(1); 781 break; 782 } 783 case ISD::XOR: { 784 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 785 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 786 787 // If all of the demanded bits are known zero on one side, return the 788 // other. 789 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 790 return Op.getOperand(0); 791 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 792 return Op.getOperand(1); 793 break; 794 } 795 case ISD::SHL: { 796 // If we are only demanding sign bits then we can use the shift source 797 // directly. 798 if (std::optional<uint64_t> MaxSA = 799 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 800 SDValue Op0 = Op.getOperand(0); 801 unsigned ShAmt = *MaxSA; 802 unsigned NumSignBits = 803 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 804 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 805 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 806 return Op0; 807 } 808 break; 809 } 810 case ISD::SRL: { 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 // Must already be signbits in DemandedBits bounds, and can't demand any 818 // shifted in zeroes. 819 if (DemandedBits.countl_zero() >= ShAmt) { 820 unsigned NumSignBits = 821 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 822 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits)) 823 return Op0; 824 } 825 } 826 break; 827 } 828 case ISD::SETCC: { 829 SDValue Op0 = Op.getOperand(0); 830 SDValue Op1 = Op.getOperand(1); 831 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 832 // If (1) we only need the sign-bit, (2) the setcc operands are the same 833 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 834 // -1, we may be able to bypass the setcc. 835 if (DemandedBits.isSignMask() && 836 Op0.getScalarValueSizeInBits() == BitWidth && 837 getBooleanContents(Op0.getValueType()) == 838 BooleanContent::ZeroOrNegativeOneBooleanContent) { 839 // If we're testing X < 0, then this compare isn't needed - just use X! 840 // FIXME: We're limiting to integer types here, but this should also work 841 // if we don't care about FP signed-zero. The use of SETLT with FP means 842 // that we don't care about NaNs. 843 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 844 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 845 return Op0; 846 } 847 break; 848 } 849 case ISD::SIGN_EXTEND_INREG: { 850 // If none of the extended bits are demanded, eliminate the sextinreg. 851 SDValue Op0 = Op.getOperand(0); 852 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 853 unsigned ExBits = ExVT.getScalarSizeInBits(); 854 if (DemandedBits.getActiveBits() <= ExBits && 855 shouldRemoveRedundantExtend(Op)) 856 return Op0; 857 // If the input is already sign extended, just drop the extension. 858 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 859 if (NumSignBits >= (BitWidth - ExBits + 1)) 860 return Op0; 861 break; 862 } 863 case ISD::ANY_EXTEND_VECTOR_INREG: 864 case ISD::SIGN_EXTEND_VECTOR_INREG: 865 case ISD::ZERO_EXTEND_VECTOR_INREG: { 866 if (VT.isScalableVector()) 867 return SDValue(); 868 869 // If we only want the lowest element and none of extended bits, then we can 870 // return the bitcasted source vector. 871 SDValue Src = Op.getOperand(0); 872 EVT SrcVT = Src.getValueType(); 873 EVT DstVT = Op.getValueType(); 874 if (IsLE && DemandedElts == 1 && 875 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 876 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 877 return DAG.getBitcast(DstVT, Src); 878 } 879 break; 880 } 881 case ISD::INSERT_VECTOR_ELT: { 882 if (VT.isScalableVector()) 883 return SDValue(); 884 885 // If we don't demand the inserted element, return the base vector. 886 SDValue Vec = Op.getOperand(0); 887 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 888 EVT VecVT = Vec.getValueType(); 889 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 890 !DemandedElts[CIdx->getZExtValue()]) 891 return Vec; 892 break; 893 } 894 case ISD::INSERT_SUBVECTOR: { 895 if (VT.isScalableVector()) 896 return SDValue(); 897 898 SDValue Vec = Op.getOperand(0); 899 SDValue Sub = Op.getOperand(1); 900 uint64_t Idx = Op.getConstantOperandVal(2); 901 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 902 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 903 // If we don't demand the inserted subvector, return the base vector. 904 if (DemandedSubElts == 0) 905 return Vec; 906 break; 907 } 908 case ISD::VECTOR_SHUFFLE: { 909 assert(!VT.isScalableVector()); 910 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 911 912 // If all the demanded elts are from one operand and are inline, 913 // then we can use the operand directly. 914 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 915 for (unsigned i = 0; i != NumElts; ++i) { 916 int M = ShuffleMask[i]; 917 if (M < 0 || !DemandedElts[i]) 918 continue; 919 AllUndef = false; 920 IdentityLHS &= (M == (int)i); 921 IdentityRHS &= ((M - NumElts) == i); 922 } 923 924 if (AllUndef) 925 return DAG.getUNDEF(Op.getValueType()); 926 if (IdentityLHS) 927 return Op.getOperand(0); 928 if (IdentityRHS) 929 return Op.getOperand(1); 930 break; 931 } 932 default: 933 // TODO: Probably okay to remove after audit; here to reduce change size 934 // in initial enablement patch for scalable vectors 935 if (VT.isScalableVector()) 936 return SDValue(); 937 938 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 939 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 940 Op, DemandedBits, DemandedElts, DAG, Depth)) 941 return V; 942 break; 943 } 944 return SDValue(); 945 } 946 947 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 948 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 949 unsigned Depth) const { 950 EVT VT = Op.getValueType(); 951 // Since the number of lanes in a scalable vector is unknown at compile time, 952 // we track one bit which is implicitly broadcast to all lanes. This means 953 // that all lanes in a scalable vector are considered demanded. 954 APInt DemandedElts = VT.isFixedLengthVector() 955 ? APInt::getAllOnes(VT.getVectorNumElements()) 956 : APInt(1, 1); 957 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 958 Depth); 959 } 960 961 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 962 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 963 unsigned Depth) const { 964 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 965 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 966 Depth); 967 } 968 969 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 970 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 971 static SDValue combineShiftToAVG(SDValue Op, 972 TargetLowering::TargetLoweringOpt &TLO, 973 const TargetLowering &TLI, 974 const APInt &DemandedBits, 975 const APInt &DemandedElts, unsigned Depth) { 976 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 977 "SRL or SRA node is required here!"); 978 // Is the right shift using an immediate value of 1? 979 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 980 if (!N1C || !N1C->isOne()) 981 return SDValue(); 982 983 // We are looking for an avgfloor 984 // add(ext, ext) 985 // or one of these as a avgceil 986 // add(add(ext, ext), 1) 987 // add(add(ext, 1), ext) 988 // add(ext, add(ext, 1)) 989 SDValue Add = Op.getOperand(0); 990 if (Add.getOpcode() != ISD::ADD) 991 return SDValue(); 992 993 SDValue ExtOpA = Add.getOperand(0); 994 SDValue ExtOpB = Add.getOperand(1); 995 SDValue Add2; 996 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) { 997 ConstantSDNode *ConstOp; 998 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 999 ConstOp->isOne()) { 1000 ExtOpA = Op1; 1001 ExtOpB = Op3; 1002 Add2 = A; 1003 return true; 1004 } 1005 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 1006 ConstOp->isOne()) { 1007 ExtOpA = Op1; 1008 ExtOpB = Op2; 1009 Add2 = A; 1010 return true; 1011 } 1012 return false; 1013 }; 1014 bool IsCeil = 1015 (ExtOpA.getOpcode() == ISD::ADD && 1016 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) || 1017 (ExtOpB.getOpcode() == ISD::ADD && 1018 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB)); 1019 1020 // If the shift is signed (sra): 1021 // - Needs >= 2 sign bit for both operands. 1022 // - Needs >= 2 zero bits. 1023 // If the shift is unsigned (srl): 1024 // - Needs >= 1 zero bit for both operands. 1025 // - Needs 1 demanded bit zero and >= 2 sign bits. 1026 SelectionDAG &DAG = TLO.DAG; 1027 unsigned ShiftOpc = Op.getOpcode(); 1028 bool IsSigned = false; 1029 unsigned KnownBits; 1030 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 1031 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 1032 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 1033 unsigned NumZeroA = 1034 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 1035 unsigned NumZeroB = 1036 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 1037 unsigned NumZero = std::min(NumZeroA, NumZeroB); 1038 1039 switch (ShiftOpc) { 1040 default: 1041 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 1042 case ISD::SRA: { 1043 if (NumZero >= 2 && NumSigned < NumZero) { 1044 IsSigned = false; 1045 KnownBits = NumZero; 1046 break; 1047 } 1048 if (NumSigned >= 1) { 1049 IsSigned = true; 1050 KnownBits = NumSigned; 1051 break; 1052 } 1053 return SDValue(); 1054 } 1055 case ISD::SRL: { 1056 if (NumZero >= 1 && NumSigned < NumZero) { 1057 IsSigned = false; 1058 KnownBits = NumZero; 1059 break; 1060 } 1061 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1062 IsSigned = true; 1063 KnownBits = NumSigned; 1064 break; 1065 } 1066 return SDValue(); 1067 } 1068 } 1069 1070 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1071 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1072 1073 // Find the smallest power-2 type that is legal for this vector size and 1074 // operation, given the original type size and the number of known sign/zero 1075 // bits. 1076 EVT VT = Op.getValueType(); 1077 unsigned MinWidth = 1078 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1079 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth)); 1080 if (NVT.getScalarSizeInBits() > VT.getScalarSizeInBits()) 1081 return SDValue(); 1082 if (VT.isVector()) 1083 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1084 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) { 1085 // If we could not transform, and (both) adds are nuw/nsw, we can use the 1086 // larger type size to do the transform. 1087 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT)) 1088 return SDValue(); 1089 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0), 1090 Add.getOperand(1)) && 1091 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0), 1092 Add2.getOperand(1)))) 1093 NVT = VT; 1094 else 1095 return SDValue(); 1096 } 1097 1098 // Don't create a AVGFLOOR node with a scalar constant unless its legal as 1099 // this is likely to stop other folds (reassociation, value tracking etc.) 1100 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) && 1101 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB))) 1102 return SDValue(); 1103 1104 SDLoc DL(Op); 1105 SDValue ResultAVG = 1106 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT), 1107 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT)); 1108 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT); 1109 } 1110 1111 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1112 /// result of Op are ever used downstream. If we can use this information to 1113 /// simplify Op, create a new simplified DAG node and return true, returning the 1114 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1115 /// return a mask of Known bits for the expression (used to simplify the 1116 /// caller). The Known bits may only be accurate for those bits in the 1117 /// OriginalDemandedBits and OriginalDemandedElts. 1118 bool TargetLowering::SimplifyDemandedBits( 1119 SDValue Op, const APInt &OriginalDemandedBits, 1120 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1121 unsigned Depth, bool AssumeSingleUse) const { 1122 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1123 assert(Op.getScalarValueSizeInBits() == BitWidth && 1124 "Mask size mismatches value type size!"); 1125 1126 // Don't know anything. 1127 Known = KnownBits(BitWidth); 1128 1129 EVT VT = Op.getValueType(); 1130 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1131 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1132 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) && 1133 "Unexpected vector size"); 1134 1135 APInt DemandedBits = OriginalDemandedBits; 1136 APInt DemandedElts = OriginalDemandedElts; 1137 SDLoc dl(Op); 1138 1139 // Undef operand. 1140 if (Op.isUndef()) 1141 return false; 1142 1143 // We can't simplify target constants. 1144 if (Op.getOpcode() == ISD::TargetConstant) 1145 return false; 1146 1147 if (Op.getOpcode() == ISD::Constant) { 1148 // We know all of the bits for a constant! 1149 Known = KnownBits::makeConstant(Op->getAsAPIntVal()); 1150 return false; 1151 } 1152 1153 if (Op.getOpcode() == ISD::ConstantFP) { 1154 // We know all of the bits for a floating point constant! 1155 Known = KnownBits::makeConstant( 1156 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1157 return false; 1158 } 1159 1160 // Other users may use these bits. 1161 bool HasMultiUse = false; 1162 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) { 1163 if (Depth >= SelectionDAG::MaxRecursionDepth) { 1164 // Limit search depth. 1165 return false; 1166 } 1167 // Allow multiple uses, just set the DemandedBits/Elts to all bits. 1168 DemandedBits = APInt::getAllOnes(BitWidth); 1169 DemandedElts = APInt::getAllOnes(NumElts); 1170 HasMultiUse = true; 1171 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1172 // Not demanding any bits/elts from Op. 1173 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1174 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1175 // Limit search depth. 1176 return false; 1177 } 1178 1179 KnownBits Known2; 1180 switch (Op.getOpcode()) { 1181 case ISD::SCALAR_TO_VECTOR: { 1182 if (VT.isScalableVector()) 1183 return false; 1184 if (!DemandedElts[0]) 1185 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1186 1187 KnownBits SrcKnown; 1188 SDValue Src = Op.getOperand(0); 1189 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1190 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1191 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1192 return true; 1193 1194 // Upper elements are undef, so only get the knownbits if we just demand 1195 // the bottom element. 1196 if (DemandedElts == 1) 1197 Known = SrcKnown.anyextOrTrunc(BitWidth); 1198 break; 1199 } 1200 case ISD::BUILD_VECTOR: 1201 // Collect the known bits that are shared by every demanded element. 1202 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1203 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1204 return false; // Don't fall through, will infinitely loop. 1205 case ISD::SPLAT_VECTOR: { 1206 SDValue Scl = Op.getOperand(0); 1207 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits()); 1208 KnownBits KnownScl; 1209 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1210 return true; 1211 1212 // Implicitly truncate the bits to match the official semantics of 1213 // SPLAT_VECTOR. 1214 Known = KnownScl.trunc(BitWidth); 1215 break; 1216 } 1217 case ISD::LOAD: { 1218 auto *LD = cast<LoadSDNode>(Op); 1219 if (getTargetConstantFromLoad(LD)) { 1220 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1221 return false; // Don't fall through, will infinitely loop. 1222 } 1223 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1224 // If this is a ZEXTLoad and we are looking at the loaded value. 1225 EVT MemVT = LD->getMemoryVT(); 1226 unsigned MemBits = MemVT.getScalarSizeInBits(); 1227 Known.Zero.setBitsFrom(MemBits); 1228 return false; // Don't fall through, will infinitely loop. 1229 } 1230 break; 1231 } 1232 case ISD::INSERT_VECTOR_ELT: { 1233 if (VT.isScalableVector()) 1234 return false; 1235 SDValue Vec = Op.getOperand(0); 1236 SDValue Scl = Op.getOperand(1); 1237 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1238 EVT VecVT = Vec.getValueType(); 1239 1240 // If index isn't constant, assume we need all vector elements AND the 1241 // inserted element. 1242 APInt DemandedVecElts(DemandedElts); 1243 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1244 unsigned Idx = CIdx->getZExtValue(); 1245 DemandedVecElts.clearBit(Idx); 1246 1247 // Inserted element is not required. 1248 if (!DemandedElts[Idx]) 1249 return TLO.CombineTo(Op, Vec); 1250 } 1251 1252 KnownBits KnownScl; 1253 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1254 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1255 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1256 return true; 1257 1258 Known = KnownScl.anyextOrTrunc(BitWidth); 1259 1260 KnownBits KnownVec; 1261 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1262 Depth + 1)) 1263 return true; 1264 1265 if (!!DemandedVecElts) 1266 Known = Known.intersectWith(KnownVec); 1267 1268 return false; 1269 } 1270 case ISD::INSERT_SUBVECTOR: { 1271 if (VT.isScalableVector()) 1272 return false; 1273 // Demand any elements from the subvector and the remainder from the src its 1274 // inserted into. 1275 SDValue Src = Op.getOperand(0); 1276 SDValue Sub = Op.getOperand(1); 1277 uint64_t Idx = Op.getConstantOperandVal(2); 1278 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1279 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1280 APInt DemandedSrcElts = DemandedElts; 1281 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1282 1283 KnownBits KnownSub, KnownSrc; 1284 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1285 Depth + 1)) 1286 return true; 1287 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1288 Depth + 1)) 1289 return true; 1290 1291 Known.Zero.setAllBits(); 1292 Known.One.setAllBits(); 1293 if (!!DemandedSubElts) 1294 Known = Known.intersectWith(KnownSub); 1295 if (!!DemandedSrcElts) 1296 Known = Known.intersectWith(KnownSrc); 1297 1298 // Attempt to avoid multi-use src if we don't need anything from it. 1299 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1300 !DemandedSrcElts.isAllOnes()) { 1301 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1302 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1303 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1304 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1305 if (NewSub || NewSrc) { 1306 NewSub = NewSub ? NewSub : Sub; 1307 NewSrc = NewSrc ? NewSrc : Src; 1308 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1309 Op.getOperand(2)); 1310 return TLO.CombineTo(Op, NewOp); 1311 } 1312 } 1313 break; 1314 } 1315 case ISD::EXTRACT_SUBVECTOR: { 1316 if (VT.isScalableVector()) 1317 return false; 1318 // Offset the demanded elts by the subvector index. 1319 SDValue Src = Op.getOperand(0); 1320 if (Src.getValueType().isScalableVector()) 1321 break; 1322 uint64_t Idx = Op.getConstantOperandVal(1); 1323 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1324 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1325 1326 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1327 Depth + 1)) 1328 return true; 1329 1330 // Attempt to avoid multi-use src if we don't need anything from it. 1331 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1332 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1333 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1334 if (DemandedSrc) { 1335 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1336 Op.getOperand(1)); 1337 return TLO.CombineTo(Op, NewOp); 1338 } 1339 } 1340 break; 1341 } 1342 case ISD::CONCAT_VECTORS: { 1343 if (VT.isScalableVector()) 1344 return false; 1345 Known.Zero.setAllBits(); 1346 Known.One.setAllBits(); 1347 EVT SubVT = Op.getOperand(0).getValueType(); 1348 unsigned NumSubVecs = Op.getNumOperands(); 1349 unsigned NumSubElts = SubVT.getVectorNumElements(); 1350 for (unsigned i = 0; i != NumSubVecs; ++i) { 1351 APInt DemandedSubElts = 1352 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1353 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1354 Known2, TLO, Depth + 1)) 1355 return true; 1356 // Known bits are shared by every demanded subvector element. 1357 if (!!DemandedSubElts) 1358 Known = Known.intersectWith(Known2); 1359 } 1360 break; 1361 } 1362 case ISD::VECTOR_SHUFFLE: { 1363 assert(!VT.isScalableVector()); 1364 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1365 1366 // Collect demanded elements from shuffle operands.. 1367 APInt DemandedLHS, DemandedRHS; 1368 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS, 1369 DemandedRHS)) 1370 break; 1371 1372 if (!!DemandedLHS || !!DemandedRHS) { 1373 SDValue Op0 = Op.getOperand(0); 1374 SDValue Op1 = Op.getOperand(1); 1375 1376 Known.Zero.setAllBits(); 1377 Known.One.setAllBits(); 1378 if (!!DemandedLHS) { 1379 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1380 Depth + 1)) 1381 return true; 1382 Known = Known.intersectWith(Known2); 1383 } 1384 if (!!DemandedRHS) { 1385 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1386 Depth + 1)) 1387 return true; 1388 Known = Known.intersectWith(Known2); 1389 } 1390 1391 // Attempt to avoid multi-use ops if we don't need anything from them. 1392 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1393 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1394 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1395 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1396 if (DemandedOp0 || DemandedOp1) { 1397 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1398 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1399 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1400 return TLO.CombineTo(Op, NewOp); 1401 } 1402 } 1403 break; 1404 } 1405 case ISD::AND: { 1406 SDValue Op0 = Op.getOperand(0); 1407 SDValue Op1 = Op.getOperand(1); 1408 1409 // If the RHS is a constant, check to see if the LHS would be zero without 1410 // using the bits from the RHS. Below, we use knowledge about the RHS to 1411 // simplify the LHS, here we're using information from the LHS to simplify 1412 // the RHS. 1413 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) { 1414 // Do not increment Depth here; that can cause an infinite loop. 1415 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1416 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1417 if ((LHSKnown.Zero & DemandedBits) == 1418 (~RHSC->getAPIntValue() & DemandedBits)) 1419 return TLO.CombineTo(Op, Op0); 1420 1421 // If any of the set bits in the RHS are known zero on the LHS, shrink 1422 // the constant. 1423 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1424 DemandedElts, TLO)) 1425 return true; 1426 1427 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1428 // constant, but if this 'and' is only clearing bits that were just set by 1429 // the xor, then this 'and' can be eliminated by shrinking the mask of 1430 // the xor. For example, for a 32-bit X: 1431 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1432 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1433 LHSKnown.One == ~RHSC->getAPIntValue()) { 1434 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1435 return TLO.CombineTo(Op, Xor); 1436 } 1437 } 1438 1439 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1440 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1441 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() && 1442 (Op0.getOperand(0).isUndef() || 1443 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1444 Op0->hasOneUse()) { 1445 unsigned NumSubElts = 1446 Op0.getOperand(1).getValueType().getVectorNumElements(); 1447 unsigned SubIdx = Op0.getConstantOperandVal(2); 1448 APInt DemandedSub = 1449 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1450 KnownBits KnownSubMask = 1451 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1452 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1453 SDValue NewAnd = 1454 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1455 SDValue NewInsert = 1456 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1457 Op0.getOperand(1), Op0.getOperand(2)); 1458 return TLO.CombineTo(Op, NewInsert); 1459 } 1460 } 1461 1462 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1463 Depth + 1)) 1464 return true; 1465 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1466 Known2, TLO, Depth + 1)) 1467 return true; 1468 1469 // If all of the demanded bits are known one on one side, return the other. 1470 // These bits cannot contribute to the result of the 'and'. 1471 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1472 return TLO.CombineTo(Op, Op0); 1473 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1474 return TLO.CombineTo(Op, Op1); 1475 // If all of the demanded bits in the inputs are known zeros, return zero. 1476 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1477 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1478 // If the RHS is a constant, see if we can simplify it. 1479 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1480 TLO)) 1481 return true; 1482 // If the operation can be done in a smaller type, do so. 1483 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1484 return true; 1485 1486 // Attempt to avoid multi-use ops if we don't need anything from them. 1487 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1488 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1489 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1490 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1491 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1492 if (DemandedOp0 || DemandedOp1) { 1493 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1494 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1495 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1496 return TLO.CombineTo(Op, NewOp); 1497 } 1498 } 1499 1500 Known &= Known2; 1501 break; 1502 } 1503 case ISD::OR: { 1504 SDValue Op0 = Op.getOperand(0); 1505 SDValue Op1 = Op.getOperand(1); 1506 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1507 Depth + 1)) { 1508 Op->dropFlags(SDNodeFlags::Disjoint); 1509 return true; 1510 } 1511 1512 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1513 Known2, TLO, Depth + 1)) { 1514 Op->dropFlags(SDNodeFlags::Disjoint); 1515 return true; 1516 } 1517 1518 // If all of the demanded bits are known zero on one side, return the other. 1519 // These bits cannot contribute to the result of the 'or'. 1520 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1521 return TLO.CombineTo(Op, Op0); 1522 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1523 return TLO.CombineTo(Op, Op1); 1524 // If the RHS is a constant, see if we can simplify it. 1525 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1526 return true; 1527 // If the operation can be done in a smaller type, do so. 1528 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1529 return true; 1530 1531 // Attempt to avoid multi-use ops if we don't need anything from them. 1532 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1533 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1534 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1535 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1536 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1537 if (DemandedOp0 || DemandedOp1) { 1538 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1539 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1540 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1541 return TLO.CombineTo(Op, NewOp); 1542 } 1543 } 1544 1545 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2)) 1546 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks. 1547 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND && 1548 Op0->hasOneUse() && Op1->hasOneUse()) { 1549 // Attempt to match all commutations - m_c_Or would've been useful! 1550 for (int I = 0; I != 2; ++I) { 1551 SDValue X = Op.getOperand(I).getOperand(0); 1552 SDValue C1 = Op.getOperand(I).getOperand(1); 1553 SDValue Alt = Op.getOperand(1 - I).getOperand(0); 1554 SDValue C2 = Op.getOperand(1 - I).getOperand(1); 1555 if (Alt.getOpcode() == ISD::OR) { 1556 for (int J = 0; J != 2; ++J) { 1557 if (X == Alt.getOperand(J)) { 1558 SDValue Y = Alt.getOperand(1 - J); 1559 if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, 1560 {C1, C2})) { 1561 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12); 1562 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2); 1563 return TLO.CombineTo( 1564 Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY)); 1565 } 1566 } 1567 } 1568 } 1569 } 1570 } 1571 1572 Known |= Known2; 1573 break; 1574 } 1575 case ISD::XOR: { 1576 SDValue Op0 = Op.getOperand(0); 1577 SDValue Op1 = Op.getOperand(1); 1578 1579 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1580 Depth + 1)) 1581 return true; 1582 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1583 Depth + 1)) 1584 return true; 1585 1586 // If all of the demanded bits are known zero on one side, return the other. 1587 // These bits cannot contribute to the result of the 'xor'. 1588 if (DemandedBits.isSubsetOf(Known.Zero)) 1589 return TLO.CombineTo(Op, Op0); 1590 if (DemandedBits.isSubsetOf(Known2.Zero)) 1591 return TLO.CombineTo(Op, Op1); 1592 // If the operation can be done in a smaller type, do so. 1593 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1594 return true; 1595 1596 // If all of the unknown bits are known to be zero on one side or the other 1597 // turn this into an *inclusive* or. 1598 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1599 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1600 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1601 1602 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts); 1603 if (C) { 1604 // If one side is a constant, and all of the set bits in the constant are 1605 // also known set on the other side, turn this into an AND, as we know 1606 // the bits will be cleared. 1607 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1608 // NB: it is okay if more bits are known than are requested 1609 if (C->getAPIntValue() == Known2.One) { 1610 SDValue ANDC = 1611 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1612 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1613 } 1614 1615 // If the RHS is a constant, see if we can change it. Don't alter a -1 1616 // constant because that's a 'not' op, and that is better for combining 1617 // and codegen. 1618 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1619 // We're flipping all demanded bits. Flip the undemanded bits too. 1620 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1621 return TLO.CombineTo(Op, New); 1622 } 1623 1624 unsigned Op0Opcode = Op0.getOpcode(); 1625 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) { 1626 if (ConstantSDNode *ShiftC = 1627 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) { 1628 // Don't crash on an oversized shift. We can not guarantee that a 1629 // bogus shift has been simplified to undef. 1630 if (ShiftC->getAPIntValue().ult(BitWidth)) { 1631 uint64_t ShiftAmt = ShiftC->getZExtValue(); 1632 APInt Ones = APInt::getAllOnes(BitWidth); 1633 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) 1634 : Ones.lshr(ShiftAmt); 1635 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) && 1636 isDesirableToCommuteXorWithShift(Op.getNode())) { 1637 // If the xor constant is a demanded mask, do a 'not' before the 1638 // shift: 1639 // xor (X << ShiftC), XorC --> (not X) << ShiftC 1640 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 1641 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT); 1642 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not, 1643 Op0.getOperand(1))); 1644 } 1645 } 1646 } 1647 } 1648 } 1649 1650 // If we can't turn this into a 'not', try to shrink the constant. 1651 if (!C || !C->isAllOnes()) 1652 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1653 return true; 1654 1655 // Attempt to avoid multi-use ops if we don't need anything from them. 1656 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1657 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1658 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1659 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1660 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1661 if (DemandedOp0 || DemandedOp1) { 1662 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1663 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1664 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1665 return TLO.CombineTo(Op, NewOp); 1666 } 1667 } 1668 1669 Known ^= Known2; 1670 break; 1671 } 1672 case ISD::SELECT: 1673 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1674 Known, TLO, Depth + 1)) 1675 return true; 1676 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1677 Known2, TLO, Depth + 1)) 1678 return true; 1679 1680 // If the operands are constants, see if we can simplify them. 1681 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1682 return true; 1683 1684 // Only known if known in both the LHS and RHS. 1685 Known = Known.intersectWith(Known2); 1686 break; 1687 case ISD::VSELECT: 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 // Only known if known in both the LHS and RHS. 1696 Known = Known.intersectWith(Known2); 1697 break; 1698 case ISD::SELECT_CC: 1699 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts, 1700 Known, TLO, Depth + 1)) 1701 return true; 1702 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1703 Known2, TLO, Depth + 1)) 1704 return true; 1705 1706 // If the operands are constants, see if we can simplify them. 1707 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 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::SETCC: { 1714 SDValue Op0 = Op.getOperand(0); 1715 SDValue Op1 = Op.getOperand(1); 1716 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1717 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1718 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1719 // -1, we may be able to bypass the setcc. 1720 if (DemandedBits.isSignMask() && 1721 Op0.getScalarValueSizeInBits() == BitWidth && 1722 getBooleanContents(Op0.getValueType()) == 1723 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1724 // If we're testing X < 0, then this compare isn't needed - just use X! 1725 // FIXME: We're limiting to integer types here, but this should also work 1726 // if we don't care about FP signed-zero. The use of SETLT with FP means 1727 // that we don't care about NaNs. 1728 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1729 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1730 return TLO.CombineTo(Op, Op0); 1731 1732 // TODO: Should we check for other forms of sign-bit comparisons? 1733 // Examples: X <= -1, X >= 0 1734 } 1735 if (getBooleanContents(Op0.getValueType()) == 1736 TargetLowering::ZeroOrOneBooleanContent && 1737 BitWidth > 1) 1738 Known.Zero.setBitsFrom(1); 1739 break; 1740 } 1741 case ISD::SHL: { 1742 SDValue Op0 = Op.getOperand(0); 1743 SDValue Op1 = Op.getOperand(1); 1744 EVT ShiftVT = Op1.getValueType(); 1745 1746 if (std::optional<uint64_t> KnownSA = 1747 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 1748 unsigned ShAmt = *KnownSA; 1749 if (ShAmt == 0) 1750 return TLO.CombineTo(Op, Op0); 1751 1752 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1753 // single shift. We can do this if the bottom bits (which are shifted 1754 // out) are never demanded. 1755 // TODO - support non-uniform vector amounts. 1756 if (Op0.getOpcode() == ISD::SRL) { 1757 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1758 if (std::optional<uint64_t> InnerSA = 1759 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1760 unsigned C1 = *InnerSA; 1761 unsigned Opc = ISD::SHL; 1762 int Diff = ShAmt - C1; 1763 if (Diff < 0) { 1764 Diff = -Diff; 1765 Opc = ISD::SRL; 1766 } 1767 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1768 return TLO.CombineTo( 1769 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1770 } 1771 } 1772 } 1773 1774 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1775 // are not demanded. This will likely allow the anyext to be folded away. 1776 // TODO - support non-uniform vector amounts. 1777 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1778 SDValue InnerOp = Op0.getOperand(0); 1779 EVT InnerVT = InnerOp.getValueType(); 1780 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1781 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1782 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1783 SDValue NarrowShl = TLO.DAG.getNode( 1784 ISD::SHL, dl, InnerVT, InnerOp, 1785 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl)); 1786 return TLO.CombineTo( 1787 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1788 } 1789 1790 // Repeat the SHL optimization above in cases where an extension 1791 // intervenes: (shl (anyext (shr x, c1)), c2) to 1792 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1793 // aren't demanded (as above) and that the shifted upper c1 bits of 1794 // x aren't demanded. 1795 // TODO - support non-uniform vector amounts. 1796 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() && 1797 InnerOp.hasOneUse()) { 1798 if (std::optional<uint64_t> SA2 = TLO.DAG.getValidShiftAmount( 1799 InnerOp, DemandedElts, Depth + 2)) { 1800 unsigned InnerShAmt = *SA2; 1801 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1802 DemandedBits.getActiveBits() <= 1803 (InnerBits - InnerShAmt + ShAmt) && 1804 DemandedBits.countr_zero() >= ShAmt) { 1805 SDValue NewSA = 1806 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1807 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1808 InnerOp.getOperand(0)); 1809 return TLO.CombineTo( 1810 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1811 } 1812 } 1813 } 1814 } 1815 1816 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1817 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1818 Depth + 1)) { 1819 // Disable the nsw and nuw flags. We can no longer guarantee that we 1820 // won't wrap after simplification. 1821 Op->dropFlags(SDNodeFlags::NoWrap); 1822 return true; 1823 } 1824 Known.Zero <<= ShAmt; 1825 Known.One <<= ShAmt; 1826 // low bits known zero. 1827 Known.Zero.setLowBits(ShAmt); 1828 1829 // Attempt to avoid multi-use ops if we don't need anything from them. 1830 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1831 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1832 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1833 if (DemandedOp0) { 1834 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1835 return TLO.CombineTo(Op, NewOp); 1836 } 1837 } 1838 1839 // TODO: Can we merge this fold with the one below? 1840 // Try shrinking the operation as long as the shift amount will still be 1841 // in range. 1842 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() && 1843 Op.getNode()->hasOneUse()) { 1844 // Search for the smallest integer type with free casts to and from 1845 // Op's type. For expedience, just check power-of-2 integer types. 1846 unsigned DemandedSize = DemandedBits.getActiveBits(); 1847 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize); 1848 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 1849 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits); 1850 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) && 1851 isTypeDesirableForOp(ISD::SHL, SmallVT) && 1852 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) && 1853 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) { 1854 assert(DemandedSize <= SmallVTBits && 1855 "Narrowed below demanded bits?"); 1856 // We found a type with free casts. 1857 SDValue NarrowShl = TLO.DAG.getNode( 1858 ISD::SHL, dl, SmallVT, 1859 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 1860 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl)); 1861 return TLO.CombineTo( 1862 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1863 } 1864 } 1865 } 1866 1867 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1868 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K)) 1869 // Only do this if we demand the upper half so the knownbits are correct. 1870 unsigned HalfWidth = BitWidth / 2; 1871 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth && 1872 DemandedBits.countLeadingOnes() >= HalfWidth) { 1873 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth); 1874 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) && 1875 isTypeDesirableForOp(ISD::SHL, HalfVT) && 1876 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 1877 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) { 1878 // If we're demanding the upper bits at all, we must ensure 1879 // that the upper bits of the shift result are known to be zero, 1880 // which is equivalent to the narrow shift being NUW. 1881 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) { 1882 bool IsNSW = Known.countMinSignBits() > HalfWidth; 1883 SDNodeFlags Flags; 1884 Flags.setNoSignedWrap(IsNSW); 1885 Flags.setNoUnsignedWrap(IsNUW); 1886 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 1887 SDValue NewShiftAmt = 1888 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl); 1889 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp, 1890 NewShiftAmt, Flags); 1891 SDValue NewExt = 1892 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift); 1893 return TLO.CombineTo(Op, NewExt); 1894 } 1895 } 1896 } 1897 } else { 1898 // This is a variable shift, so we can't shift the demand mask by a known 1899 // amount. But if we are not demanding high bits, then we are not 1900 // demanding those bits from the pre-shifted operand either. 1901 if (unsigned CTLZ = DemandedBits.countl_zero()) { 1902 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1903 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1904 Depth + 1)) { 1905 // Disable the nsw and nuw flags. We can no longer guarantee that we 1906 // won't wrap after simplification. 1907 Op->dropFlags(SDNodeFlags::NoWrap); 1908 return true; 1909 } 1910 Known.resetAll(); 1911 } 1912 } 1913 1914 // If we are only demanding sign bits then we can use the shift source 1915 // directly. 1916 if (std::optional<uint64_t> MaxSA = 1917 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) { 1918 unsigned ShAmt = *MaxSA; 1919 unsigned NumSignBits = 1920 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1921 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 1922 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1923 return TLO.CombineTo(Op, Op0); 1924 } 1925 break; 1926 } 1927 case ISD::SRL: { 1928 SDValue Op0 = Op.getOperand(0); 1929 SDValue Op1 = Op.getOperand(1); 1930 EVT ShiftVT = Op1.getValueType(); 1931 1932 if (std::optional<uint64_t> KnownSA = 1933 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 1934 unsigned ShAmt = *KnownSA; 1935 if (ShAmt == 0) 1936 return TLO.CombineTo(Op, Op0); 1937 1938 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1939 // single shift. We can do this if the top bits (which are shifted out) 1940 // are never demanded. 1941 // TODO - support non-uniform vector amounts. 1942 if (Op0.getOpcode() == ISD::SHL) { 1943 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1944 if (std::optional<uint64_t> InnerSA = 1945 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1946 unsigned C1 = *InnerSA; 1947 unsigned Opc = ISD::SRL; 1948 int Diff = ShAmt - C1; 1949 if (Diff < 0) { 1950 Diff = -Diff; 1951 Opc = ISD::SHL; 1952 } 1953 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1954 return TLO.CombineTo( 1955 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1956 } 1957 } 1958 } 1959 1960 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a 1961 // single sra. We can do this if the top bits are never demanded. 1962 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) { 1963 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1964 if (std::optional<uint64_t> InnerSA = 1965 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 1966 unsigned C1 = *InnerSA; 1967 // Clamp the combined shift amount if it exceeds the bit width. 1968 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1); 1969 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT); 1970 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT, 1971 Op0.getOperand(0), NewSA)); 1972 } 1973 } 1974 } 1975 1976 APInt InDemandedMask = (DemandedBits << ShAmt); 1977 1978 // If the shift is exact, then it does demand the low bits (and knows that 1979 // they are zero). 1980 if (Op->getFlags().hasExact()) 1981 InDemandedMask.setLowBits(ShAmt); 1982 1983 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1984 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K)) 1985 if ((BitWidth % 2) == 0 && !VT.isVector()) { 1986 APInt HiBits = APInt::getHighBitsSet(BitWidth, BitWidth / 2); 1987 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2); 1988 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) && 1989 isTypeDesirableForOp(ISD::SRL, HalfVT) && 1990 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 1991 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) && 1992 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) || 1993 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) { 1994 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 1995 SDValue NewShiftAmt = 1996 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl); 1997 SDValue NewShift = 1998 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt); 1999 return TLO.CombineTo( 2000 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift)); 2001 } 2002 } 2003 2004 // Compute the new bits that are at the top now. 2005 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 2006 Depth + 1)) 2007 return true; 2008 Known.Zero.lshrInPlace(ShAmt); 2009 Known.One.lshrInPlace(ShAmt); 2010 // High bits known zero. 2011 Known.Zero.setHighBits(ShAmt); 2012 2013 // Attempt to avoid multi-use ops if we don't need anything from them. 2014 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2015 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2016 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 2017 if (DemandedOp0) { 2018 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1); 2019 return TLO.CombineTo(Op, NewOp); 2020 } 2021 } 2022 } else { 2023 // Use generic knownbits computation as it has support for non-uniform 2024 // shift amounts. 2025 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2026 } 2027 2028 // Try to match AVG patterns (after shift simplification). 2029 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits, 2030 DemandedElts, Depth + 1)) 2031 return TLO.CombineTo(Op, AVG); 2032 2033 break; 2034 } 2035 case ISD::SRA: { 2036 SDValue Op0 = Op.getOperand(0); 2037 SDValue Op1 = Op.getOperand(1); 2038 EVT ShiftVT = Op1.getValueType(); 2039 2040 // If we only want bits that already match the signbit then we don't need 2041 // to shift. 2042 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero(); 2043 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 2044 NumHiDemandedBits) 2045 return TLO.CombineTo(Op, Op0); 2046 2047 // If this is an arithmetic shift right and only the low-bit is set, we can 2048 // always convert this into a logical shr, even if the shift amount is 2049 // variable. The low bit of the shift cannot be an input sign bit unless 2050 // the shift amount is >= the size of the datatype, which is undefined. 2051 if (DemandedBits.isOne()) 2052 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2053 2054 if (std::optional<uint64_t> KnownSA = 2055 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) { 2056 unsigned ShAmt = *KnownSA; 2057 if (ShAmt == 0) 2058 return TLO.CombineTo(Op, Op0); 2059 2060 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target 2061 // supports sext_inreg. 2062 if (Op0.getOpcode() == ISD::SHL) { 2063 if (std::optional<uint64_t> InnerSA = 2064 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) { 2065 unsigned LowBits = BitWidth - ShAmt; 2066 EVT ExtVT = EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits); 2067 if (VT.isVector()) 2068 ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtVT, 2069 VT.getVectorElementCount()); 2070 2071 if (*InnerSA == ShAmt) { 2072 if (!TLO.LegalOperations() || 2073 getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == Legal) 2074 return TLO.CombineTo( 2075 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, 2076 Op0.getOperand(0), 2077 TLO.DAG.getValueType(ExtVT))); 2078 2079 // Even if we can't convert to sext_inreg, we might be able to 2080 // remove this shift pair if the input is already sign extended. 2081 unsigned NumSignBits = 2082 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts); 2083 if (NumSignBits > ShAmt) 2084 return TLO.CombineTo(Op, Op0.getOperand(0)); 2085 } 2086 } 2087 } 2088 2089 APInt InDemandedMask = (DemandedBits << ShAmt); 2090 2091 // If the shift is exact, then it does demand the low bits (and knows that 2092 // they are zero). 2093 if (Op->getFlags().hasExact()) 2094 InDemandedMask.setLowBits(ShAmt); 2095 2096 // If any of the demanded bits are produced by the sign extension, we also 2097 // demand the input sign bit. 2098 if (DemandedBits.countl_zero() < ShAmt) 2099 InDemandedMask.setSignBit(); 2100 2101 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 2102 Depth + 1)) 2103 return true; 2104 Known.Zero.lshrInPlace(ShAmt); 2105 Known.One.lshrInPlace(ShAmt); 2106 2107 // If the input sign bit is known to be zero, or if none of the top bits 2108 // are demanded, turn this into an unsigned shift right. 2109 if (Known.Zero[BitWidth - ShAmt - 1] || 2110 DemandedBits.countl_zero() >= ShAmt) { 2111 SDNodeFlags Flags; 2112 Flags.setExact(Op->getFlags().hasExact()); 2113 return TLO.CombineTo( 2114 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 2115 } 2116 2117 int Log2 = DemandedBits.exactLogBase2(); 2118 if (Log2 >= 0) { 2119 // The bit must come from the sign. 2120 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 2121 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 2122 } 2123 2124 if (Known.One[BitWidth - ShAmt - 1]) 2125 // New bits are known one. 2126 Known.One.setHighBits(ShAmt); 2127 2128 // Attempt to avoid multi-use ops if we don't need anything from them. 2129 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2130 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2131 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 2132 if (DemandedOp0) { 2133 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 2134 return TLO.CombineTo(Op, NewOp); 2135 } 2136 } 2137 } 2138 2139 // Try to match AVG patterns (after shift simplification). 2140 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits, 2141 DemandedElts, Depth + 1)) 2142 return TLO.CombineTo(Op, AVG); 2143 2144 break; 2145 } 2146 case ISD::FSHL: 2147 case ISD::FSHR: { 2148 SDValue Op0 = Op.getOperand(0); 2149 SDValue Op1 = Op.getOperand(1); 2150 SDValue Op2 = Op.getOperand(2); 2151 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 2152 2153 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 2154 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2155 2156 // For fshl, 0-shift returns the 1st arg. 2157 // For fshr, 0-shift returns the 2nd arg. 2158 if (Amt == 0) { 2159 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 2160 Known, TLO, Depth + 1)) 2161 return true; 2162 break; 2163 } 2164 2165 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 2166 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 2167 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 2168 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 2169 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2170 Depth + 1)) 2171 return true; 2172 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 2173 Depth + 1)) 2174 return true; 2175 2176 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2177 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2178 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2179 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2180 Known = Known.unionWith(Known2); 2181 2182 // Attempt to avoid multi-use ops if we don't need anything from them. 2183 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 2184 !DemandedElts.isAllOnes()) { 2185 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2186 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 2187 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2188 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 2189 if (DemandedOp0 || DemandedOp1) { 2190 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 2191 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 2192 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 2193 DemandedOp1, Op2); 2194 return TLO.CombineTo(Op, NewOp); 2195 } 2196 } 2197 } 2198 2199 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2200 if (isPowerOf2_32(BitWidth)) { 2201 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 2202 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 2203 Known2, TLO, Depth + 1)) 2204 return true; 2205 } 2206 break; 2207 } 2208 case ISD::ROTL: 2209 case ISD::ROTR: { 2210 SDValue Op0 = Op.getOperand(0); 2211 SDValue Op1 = Op.getOperand(1); 2212 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 2213 2214 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 2215 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 2216 return TLO.CombineTo(Op, Op0); 2217 2218 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 2219 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2220 unsigned RevAmt = BitWidth - Amt; 2221 2222 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 2223 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 2224 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 2225 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2226 Depth + 1)) 2227 return true; 2228 2229 // rot*(x, 0) --> x 2230 if (Amt == 0) 2231 return TLO.CombineTo(Op, Op0); 2232 2233 // See if we don't demand either half of the rotated bits. 2234 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 2235 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) { 2236 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 2237 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 2238 } 2239 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 2240 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) { 2241 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 2242 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2243 } 2244 } 2245 2246 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2247 if (isPowerOf2_32(BitWidth)) { 2248 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2249 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2250 Depth + 1)) 2251 return true; 2252 } 2253 break; 2254 } 2255 case ISD::SMIN: 2256 case ISD::SMAX: 2257 case ISD::UMIN: 2258 case ISD::UMAX: { 2259 unsigned Opc = Op.getOpcode(); 2260 SDValue Op0 = Op.getOperand(0); 2261 SDValue Op1 = Op.getOperand(1); 2262 2263 // If we're only demanding signbits, then we can simplify to OR/AND node. 2264 unsigned BitOp = 2265 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND; 2266 unsigned NumSignBits = 2267 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1), 2268 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1)); 2269 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero(); 2270 if (NumSignBits >= NumDemandedUpperBits) 2271 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1)); 2272 2273 // Check if one arg is always less/greater than (or equal) to the other arg. 2274 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2275 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2276 switch (Opc) { 2277 case ISD::SMIN: 2278 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1)) 2279 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1); 2280 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1)) 2281 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1); 2282 Known = KnownBits::smin(Known0, Known1); 2283 break; 2284 case ISD::SMAX: 2285 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1)) 2286 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1); 2287 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1)) 2288 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1); 2289 Known = KnownBits::smax(Known0, Known1); 2290 break; 2291 case ISD::UMIN: 2292 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2293 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1); 2294 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2295 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1); 2296 Known = KnownBits::umin(Known0, Known1); 2297 break; 2298 case ISD::UMAX: 2299 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2300 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1); 2301 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2302 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1); 2303 Known = KnownBits::umax(Known0, Known1); 2304 break; 2305 } 2306 break; 2307 } 2308 case ISD::BITREVERSE: { 2309 SDValue Src = Op.getOperand(0); 2310 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2311 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2312 Depth + 1)) 2313 return true; 2314 Known.One = Known2.One.reverseBits(); 2315 Known.Zero = Known2.Zero.reverseBits(); 2316 break; 2317 } 2318 case ISD::BSWAP: { 2319 SDValue Src = Op.getOperand(0); 2320 2321 // If the only bits demanded come from one byte of the bswap result, 2322 // just shift the input byte into position to eliminate the bswap. 2323 unsigned NLZ = DemandedBits.countl_zero(); 2324 unsigned NTZ = DemandedBits.countr_zero(); 2325 2326 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2327 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2328 // have 14 leading zeros, round to 8. 2329 NLZ = alignDown(NLZ, 8); 2330 NTZ = alignDown(NTZ, 8); 2331 // If we need exactly one byte, we can do this transformation. 2332 if (BitWidth - NLZ - NTZ == 8) { 2333 // Replace this with either a left or right shift to get the byte into 2334 // the right place. 2335 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2336 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2337 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2338 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl); 2339 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2340 return TLO.CombineTo(Op, NewOp); 2341 } 2342 } 2343 2344 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2345 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2346 Depth + 1)) 2347 return true; 2348 Known.One = Known2.One.byteSwap(); 2349 Known.Zero = Known2.Zero.byteSwap(); 2350 break; 2351 } 2352 case ISD::CTPOP: { 2353 // If only 1 bit is demanded, replace with PARITY as long as we're before 2354 // op legalization. 2355 // FIXME: Limit to scalars for now. 2356 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2357 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2358 Op.getOperand(0))); 2359 2360 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2361 break; 2362 } 2363 case ISD::SIGN_EXTEND_INREG: { 2364 SDValue Op0 = Op.getOperand(0); 2365 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2366 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2367 2368 // If we only care about the highest bit, don't bother shifting right. 2369 if (DemandedBits.isSignMask()) { 2370 unsigned MinSignedBits = 2371 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2372 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2373 // However if the input is already sign extended we expect the sign 2374 // extension to be dropped altogether later and do not simplify. 2375 if (!AlreadySignExtended) { 2376 // Compute the correct shift amount type, which must be getShiftAmountTy 2377 // for scalar types after legalization. 2378 SDValue ShiftAmt = 2379 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl); 2380 return TLO.CombineTo(Op, 2381 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2382 } 2383 } 2384 2385 // If none of the extended bits are demanded, eliminate the sextinreg. 2386 if (DemandedBits.getActiveBits() <= ExVTBits) 2387 return TLO.CombineTo(Op, Op0); 2388 2389 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2390 2391 // Since the sign extended bits are demanded, we know that the sign 2392 // bit is demanded. 2393 InputDemandedBits.setBit(ExVTBits - 1); 2394 2395 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2396 Depth + 1)) 2397 return true; 2398 2399 // If the sign bit of the input is known set or clear, then we know the 2400 // top bits of the result. 2401 2402 // If the input sign bit is known zero, convert this into a zero extension. 2403 if (Known.Zero[ExVTBits - 1]) 2404 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2405 2406 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2407 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2408 Known.One.setBitsFrom(ExVTBits); 2409 Known.Zero &= Mask; 2410 } else { // Input sign bit unknown 2411 Known.Zero &= Mask; 2412 Known.One &= Mask; 2413 } 2414 break; 2415 } 2416 case ISD::BUILD_PAIR: { 2417 EVT HalfVT = Op.getOperand(0).getValueType(); 2418 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2419 2420 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2421 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2422 2423 KnownBits KnownLo, KnownHi; 2424 2425 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2426 return true; 2427 2428 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2429 return true; 2430 2431 Known = KnownHi.concat(KnownLo); 2432 break; 2433 } 2434 case ISD::ZERO_EXTEND_VECTOR_INREG: 2435 if (VT.isScalableVector()) 2436 return false; 2437 [[fallthrough]]; 2438 case ISD::ZERO_EXTEND: { 2439 SDValue Src = Op.getOperand(0); 2440 EVT SrcVT = Src.getValueType(); 2441 unsigned InBits = SrcVT.getScalarSizeInBits(); 2442 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2443 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2444 2445 // If none of the top bits are demanded, convert this into an any_extend. 2446 if (DemandedBits.getActiveBits() <= InBits) { 2447 // If we only need the non-extended bits of the bottom element 2448 // then we can just bitcast to the result. 2449 if (IsLE && IsVecInReg && DemandedElts == 1 && 2450 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2451 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2452 2453 unsigned Opc = 2454 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2455 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2456 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2457 } 2458 2459 APInt InDemandedBits = DemandedBits.trunc(InBits); 2460 APInt InDemandedElts = DemandedElts.zext(InElts); 2461 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2462 Depth + 1)) { 2463 Op->dropFlags(SDNodeFlags::NonNeg); 2464 return true; 2465 } 2466 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2467 Known = Known.zext(BitWidth); 2468 2469 // Attempt to avoid multi-use ops if we don't need anything from them. 2470 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2471 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2472 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2473 break; 2474 } 2475 case ISD::SIGN_EXTEND_VECTOR_INREG: 2476 if (VT.isScalableVector()) 2477 return false; 2478 [[fallthrough]]; 2479 case ISD::SIGN_EXTEND: { 2480 SDValue Src = Op.getOperand(0); 2481 EVT SrcVT = Src.getValueType(); 2482 unsigned InBits = SrcVT.getScalarSizeInBits(); 2483 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2484 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2485 2486 APInt InDemandedElts = DemandedElts.zext(InElts); 2487 APInt InDemandedBits = DemandedBits.trunc(InBits); 2488 2489 // Since some of the sign extended bits are demanded, we know that the sign 2490 // bit is demanded. 2491 InDemandedBits.setBit(InBits - 1); 2492 2493 // If none of the top bits are demanded, convert this into an any_extend. 2494 if (DemandedBits.getActiveBits() <= InBits) { 2495 // If we only need the non-extended bits of the bottom element 2496 // then we can just bitcast to the result. 2497 if (IsLE && IsVecInReg && DemandedElts == 1 && 2498 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2499 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2500 2501 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans. 2502 if (getBooleanContents(VT) != ZeroOrNegativeOneBooleanContent || 2503 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) != 2504 InBits) { 2505 unsigned Opc = 2506 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2507 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2508 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2509 } 2510 } 2511 2512 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2513 Depth + 1)) 2514 return true; 2515 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2516 2517 // If the sign bit is known one, the top bits match. 2518 Known = Known.sext(BitWidth); 2519 2520 // If the sign bit is known zero, convert this to a zero extend. 2521 if (Known.isNonNegative()) { 2522 unsigned Opc = 2523 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2524 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) { 2525 SDNodeFlags Flags; 2526 if (!IsVecInReg) 2527 Flags |= SDNodeFlags::NonNeg; 2528 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags)); 2529 } 2530 } 2531 2532 // Attempt to avoid multi-use ops if we don't need anything from them. 2533 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2534 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2535 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2536 break; 2537 } 2538 case ISD::ANY_EXTEND_VECTOR_INREG: 2539 if (VT.isScalableVector()) 2540 return false; 2541 [[fallthrough]]; 2542 case ISD::ANY_EXTEND: { 2543 SDValue Src = Op.getOperand(0); 2544 EVT SrcVT = Src.getValueType(); 2545 unsigned InBits = SrcVT.getScalarSizeInBits(); 2546 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2547 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2548 2549 // If we only need the bottom element then we can just bitcast. 2550 // TODO: Handle ANY_EXTEND? 2551 if (IsLE && IsVecInReg && DemandedElts == 1 && 2552 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2553 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2554 2555 APInt InDemandedBits = DemandedBits.trunc(InBits); 2556 APInt InDemandedElts = DemandedElts.zext(InElts); 2557 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2558 Depth + 1)) 2559 return true; 2560 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2561 Known = Known.anyext(BitWidth); 2562 2563 // Attempt to avoid multi-use ops if we don't need anything from them. 2564 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2565 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2566 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2567 break; 2568 } 2569 case ISD::TRUNCATE: { 2570 SDValue Src = Op.getOperand(0); 2571 2572 // Simplify the input, using demanded bit information, and compute the known 2573 // zero/one bits live out. 2574 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2575 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2576 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2577 Depth + 1)) 2578 return true; 2579 Known = Known.trunc(BitWidth); 2580 2581 // Attempt to avoid multi-use ops if we don't need anything from them. 2582 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2583 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2584 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2585 2586 // If the input is only used by this truncate, see if we can shrink it based 2587 // on the known demanded bits. 2588 switch (Src.getOpcode()) { 2589 default: 2590 break; 2591 case ISD::SRL: 2592 // Shrink SRL by a constant if none of the high bits shifted in are 2593 // demanded. 2594 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2595 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2596 // undesirable. 2597 break; 2598 2599 if (Src.getNode()->hasOneUse()) { 2600 if (isTruncateFree(Src, VT) && 2601 !isTruncateFree(Src.getValueType(), VT)) { 2602 // If truncate is only free at trunc(srl), do not turn it into 2603 // srl(trunc). The check is done by first check the truncate is free 2604 // at Src's opcode(srl), then check the truncate is not done by 2605 // referencing sub-register. In test, if both trunc(srl) and 2606 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only 2607 // trunc(srl)'s trunc is free, trunc(srl) is better. 2608 break; 2609 } 2610 2611 std::optional<uint64_t> ShAmtC = 2612 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2); 2613 if (!ShAmtC || *ShAmtC >= BitWidth) 2614 break; 2615 uint64_t ShVal = *ShAmtC; 2616 2617 APInt HighBits = 2618 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2619 HighBits.lshrInPlace(ShVal); 2620 HighBits = HighBits.trunc(BitWidth); 2621 if (!(HighBits & DemandedBits)) { 2622 // None of the shifted in bits are needed. Add a truncate of the 2623 // shift input, then shift it. 2624 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl); 2625 SDValue NewTrunc = 2626 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2627 return TLO.CombineTo( 2628 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2629 } 2630 } 2631 break; 2632 } 2633 2634 break; 2635 } 2636 case ISD::AssertZext: { 2637 // AssertZext demands all of the high bits, plus any of the low bits 2638 // demanded by its users. 2639 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2640 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2641 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2642 TLO, Depth + 1)) 2643 return true; 2644 2645 Known.Zero |= ~InMask; 2646 Known.One &= (~Known.Zero); 2647 break; 2648 } 2649 case ISD::EXTRACT_VECTOR_ELT: { 2650 SDValue Src = Op.getOperand(0); 2651 SDValue Idx = Op.getOperand(1); 2652 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2653 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2654 2655 if (SrcEltCnt.isScalable()) 2656 return false; 2657 2658 // Demand the bits from every vector element without a constant index. 2659 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2660 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2661 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2662 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2663 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2664 2665 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2666 // anything about the extended bits. 2667 APInt DemandedSrcBits = DemandedBits; 2668 if (BitWidth > EltBitWidth) 2669 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2670 2671 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2672 Depth + 1)) 2673 return true; 2674 2675 // Attempt to avoid multi-use ops if we don't need anything from them. 2676 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2677 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2678 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2679 SDValue NewOp = 2680 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2681 return TLO.CombineTo(Op, NewOp); 2682 } 2683 } 2684 2685 Known = Known2; 2686 if (BitWidth > EltBitWidth) 2687 Known = Known.anyext(BitWidth); 2688 break; 2689 } 2690 case ISD::BITCAST: { 2691 if (VT.isScalableVector()) 2692 return false; 2693 SDValue Src = Op.getOperand(0); 2694 EVT SrcVT = Src.getValueType(); 2695 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2696 2697 // If this is an FP->Int bitcast and if the sign bit is the only 2698 // thing demanded, turn this into a FGETSIGN. 2699 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2700 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2701 SrcVT.isFloatingPoint()) { 2702 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2703 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2704 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2705 SrcVT != MVT::f128) { 2706 // Cannot eliminate/lower SHL for f128 yet. 2707 EVT Ty = OpVTLegal ? VT : MVT::i32; 2708 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2709 // place. We expect the SHL to be eliminated by other optimizations. 2710 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2711 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2712 if (!OpVTLegal && OpVTSizeInBits > 32) 2713 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2714 unsigned ShVal = Op.getValueSizeInBits() - 1; 2715 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2716 return TLO.CombineTo(Op, 2717 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2718 } 2719 } 2720 2721 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2722 // Demand the elt/bit if any of the original elts/bits are demanded. 2723 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2724 unsigned Scale = BitWidth / NumSrcEltBits; 2725 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2726 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2727 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2728 for (unsigned i = 0; i != Scale; ++i) { 2729 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2730 unsigned BitOffset = EltOffset * NumSrcEltBits; 2731 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2732 if (!Sub.isZero()) { 2733 DemandedSrcBits |= Sub; 2734 for (unsigned j = 0; j != NumElts; ++j) 2735 if (DemandedElts[j]) 2736 DemandedSrcElts.setBit((j * Scale) + i); 2737 } 2738 } 2739 2740 APInt KnownSrcUndef, KnownSrcZero; 2741 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2742 KnownSrcZero, TLO, Depth + 1)) 2743 return true; 2744 2745 KnownBits KnownSrcBits; 2746 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2747 KnownSrcBits, TLO, Depth + 1)) 2748 return true; 2749 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2750 // TODO - bigendian once we have test coverage. 2751 unsigned Scale = NumSrcEltBits / BitWidth; 2752 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2753 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2754 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2755 for (unsigned i = 0; i != NumElts; ++i) 2756 if (DemandedElts[i]) { 2757 unsigned Offset = (i % Scale) * BitWidth; 2758 DemandedSrcBits.insertBits(DemandedBits, Offset); 2759 DemandedSrcElts.setBit(i / Scale); 2760 } 2761 2762 if (SrcVT.isVector()) { 2763 APInt KnownSrcUndef, KnownSrcZero; 2764 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2765 KnownSrcZero, TLO, Depth + 1)) 2766 return true; 2767 } 2768 2769 KnownBits KnownSrcBits; 2770 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2771 KnownSrcBits, TLO, Depth + 1)) 2772 return true; 2773 2774 // Attempt to avoid multi-use ops if we don't need anything from them. 2775 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2776 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2777 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2778 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc); 2779 return TLO.CombineTo(Op, NewOp); 2780 } 2781 } 2782 } 2783 2784 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2785 // recursive call where Known may be useful to the caller. 2786 if (Depth > 0) { 2787 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2788 return false; 2789 } 2790 break; 2791 } 2792 case ISD::MUL: 2793 if (DemandedBits.isPowerOf2()) { 2794 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2795 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2796 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2797 unsigned CTZ = DemandedBits.countr_zero(); 2798 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2799 if (C && C->getAPIntValue().countr_zero() == CTZ) { 2800 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl); 2801 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2802 return TLO.CombineTo(Op, Shl); 2803 } 2804 } 2805 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2806 // X * X is odd iff X is odd. 2807 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2808 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2809 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2810 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2811 return TLO.CombineTo(Op, And1); 2812 } 2813 [[fallthrough]]; 2814 case ISD::ADD: 2815 case ISD::SUB: { 2816 // Add, Sub, and Mul don't demand any bits in positions beyond that 2817 // of the highest bit demanded of them. 2818 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2819 SDNodeFlags Flags = Op.getNode()->getFlags(); 2820 unsigned DemandedBitsLZ = DemandedBits.countl_zero(); 2821 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2822 KnownBits KnownOp0, KnownOp1; 2823 auto GetDemandedBitsLHSMask = [&](APInt Demanded, 2824 const KnownBits &KnownRHS) { 2825 if (Op.getOpcode() == ISD::MUL) 2826 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros()); 2827 return Demanded; 2828 }; 2829 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO, 2830 Depth + 1) || 2831 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1), 2832 DemandedElts, KnownOp0, TLO, Depth + 1) || 2833 // See if the operation should be performed at a smaller bit width. 2834 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2835 // Disable the nsw and nuw flags. We can no longer guarantee that we 2836 // won't wrap after simplification. 2837 Op->dropFlags(SDNodeFlags::NoWrap); 2838 return true; 2839 } 2840 2841 // neg x with only low bit demanded is simply x. 2842 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() && 2843 isNullConstant(Op0)) 2844 return TLO.CombineTo(Op, Op1); 2845 2846 // Attempt to avoid multi-use ops if we don't need anything from them. 2847 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2848 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2849 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2850 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2851 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2852 if (DemandedOp0 || DemandedOp1) { 2853 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2854 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2855 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, 2856 Flags & ~SDNodeFlags::NoWrap); 2857 return TLO.CombineTo(Op, NewOp); 2858 } 2859 } 2860 2861 // If we have a constant operand, we may be able to turn it into -1 if we 2862 // do not demand the high bits. This can make the constant smaller to 2863 // encode, allow more general folding, or match specialized instruction 2864 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2865 // is probably not useful (and could be detrimental). 2866 ConstantSDNode *C = isConstOrConstSplat(Op1); 2867 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2868 if (C && !C->isAllOnes() && !C->isOne() && 2869 (C->getAPIntValue() | HighMask).isAllOnes()) { 2870 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2871 // Disable the nsw and nuw flags. We can no longer guarantee that we 2872 // won't wrap after simplification. 2873 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, 2874 Flags & ~SDNodeFlags::NoWrap); 2875 return TLO.CombineTo(Op, NewOp); 2876 } 2877 2878 // Match a multiply with a disguised negated-power-of-2 and convert to a 2879 // an equivalent shift-left amount. 2880 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2881 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2882 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2883 return 0; 2884 2885 // Don't touch opaque constants. Also, ignore zero and power-of-2 2886 // multiplies. Those will get folded later. 2887 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2888 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2889 !MulC->getAPIntValue().isPowerOf2()) { 2890 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2891 if (UnmaskedC.isNegatedPowerOf2()) 2892 return (-UnmaskedC).logBase2(); 2893 } 2894 return 0; 2895 }; 2896 2897 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, 2898 unsigned ShlAmt) { 2899 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl); 2900 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2901 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2902 return TLO.CombineTo(Op, Res); 2903 }; 2904 2905 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2906 if (Op.getOpcode() == ISD::ADD) { 2907 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2908 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2909 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2910 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2911 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2912 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2913 } 2914 if (Op.getOpcode() == ISD::SUB) { 2915 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2916 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2917 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2918 } 2919 } 2920 2921 if (Op.getOpcode() == ISD::MUL) { 2922 Known = KnownBits::mul(KnownOp0, KnownOp1); 2923 } else { // Op.getOpcode() is either ISD::ADD or ISD::SUB. 2924 Known = KnownBits::computeForAddSub( 2925 Op.getOpcode() == ISD::ADD, Flags.hasNoSignedWrap(), 2926 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1); 2927 } 2928 break; 2929 } 2930 default: 2931 // We also ask the target about intrinsics (which could be specific to it). 2932 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2933 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 2934 // TODO: Probably okay to remove after audit; here to reduce change size 2935 // in initial enablement patch for scalable vectors 2936 if (Op.getValueType().isScalableVector()) 2937 break; 2938 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2939 Known, TLO, Depth)) 2940 return true; 2941 break; 2942 } 2943 2944 // Just use computeKnownBits to compute output bits. 2945 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2946 break; 2947 } 2948 2949 // If we know the value of all of the demanded bits, return this as a 2950 // constant. 2951 if (!isTargetCanonicalConstantNode(Op) && 2952 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2953 // Avoid folding to a constant if any OpaqueConstant is involved. 2954 const SDNode *N = Op.getNode(); 2955 for (SDNode *Op : 2956 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2957 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 2958 if (C->isOpaque()) 2959 return false; 2960 } 2961 if (VT.isInteger()) 2962 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2963 if (VT.isFloatingPoint()) 2964 return TLO.CombineTo( 2965 Op, TLO.DAG.getConstantFP(APFloat(VT.getFltSemantics(), Known.One), 2966 dl, VT)); 2967 } 2968 2969 // A multi use 'all demanded elts' simplify failed to find any knownbits. 2970 // Try again just for the original demanded elts. 2971 // Ensure we do this AFTER constant folding above. 2972 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes()) 2973 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth); 2974 2975 return false; 2976 } 2977 2978 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2979 const APInt &DemandedElts, 2980 DAGCombinerInfo &DCI) const { 2981 SelectionDAG &DAG = DCI.DAG; 2982 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2983 !DCI.isBeforeLegalizeOps()); 2984 2985 APInt KnownUndef, KnownZero; 2986 bool Simplified = 2987 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2988 if (Simplified) { 2989 DCI.AddToWorklist(Op.getNode()); 2990 DCI.CommitTargetLoweringOpt(TLO); 2991 } 2992 2993 return Simplified; 2994 } 2995 2996 /// Given a vector binary operation and known undefined elements for each input 2997 /// operand, compute whether each element of the output is undefined. 2998 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2999 const APInt &UndefOp0, 3000 const APInt &UndefOp1) { 3001 EVT VT = BO.getValueType(); 3002 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 3003 "Vector binop only"); 3004 3005 EVT EltVT = VT.getVectorElementType(); 3006 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1; 3007 assert(UndefOp0.getBitWidth() == NumElts && 3008 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 3009 3010 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 3011 const APInt &UndefVals) { 3012 if (UndefVals[Index]) 3013 return DAG.getUNDEF(EltVT); 3014 3015 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 3016 // Try hard to make sure that the getNode() call is not creating temporary 3017 // nodes. Ignore opaque integers because they do not constant fold. 3018 SDValue Elt = BV->getOperand(Index); 3019 auto *C = dyn_cast<ConstantSDNode>(Elt); 3020 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 3021 return Elt; 3022 } 3023 3024 return SDValue(); 3025 }; 3026 3027 APInt KnownUndef = APInt::getZero(NumElts); 3028 for (unsigned i = 0; i != NumElts; ++i) { 3029 // If both inputs for this element are either constant or undef and match 3030 // the element type, compute the constant/undef result for this element of 3031 // the vector. 3032 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 3033 // not handle FP constants. The code within getNode() should be refactored 3034 // to avoid the danger of creating a bogus temporary node here. 3035 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 3036 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 3037 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 3038 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 3039 KnownUndef.setBit(i); 3040 } 3041 return KnownUndef; 3042 } 3043 3044 bool TargetLowering::SimplifyDemandedVectorElts( 3045 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 3046 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 3047 bool AssumeSingleUse) const { 3048 EVT VT = Op.getValueType(); 3049 unsigned Opcode = Op.getOpcode(); 3050 APInt DemandedElts = OriginalDemandedElts; 3051 unsigned NumElts = DemandedElts.getBitWidth(); 3052 assert(VT.isVector() && "Expected vector op"); 3053 3054 KnownUndef = KnownZero = APInt::getZero(NumElts); 3055 3056 if (!shouldSimplifyDemandedVectorElts(Op, TLO)) 3057 return false; 3058 3059 // TODO: For now we assume we know nothing about scalable vectors. 3060 if (VT.isScalableVector()) 3061 return false; 3062 3063 assert(VT.getVectorNumElements() == NumElts && 3064 "Mask size mismatches value type element count!"); 3065 3066 // Undef operand. 3067 if (Op.isUndef()) { 3068 KnownUndef.setAllBits(); 3069 return false; 3070 } 3071 3072 // If Op has other users, assume that all elements are needed. 3073 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) 3074 DemandedElts.setAllBits(); 3075 3076 // Not demanding any elements from Op. 3077 if (DemandedElts == 0) { 3078 KnownUndef.setAllBits(); 3079 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3080 } 3081 3082 // Limit search depth. 3083 if (Depth >= SelectionDAG::MaxRecursionDepth) 3084 return false; 3085 3086 SDLoc DL(Op); 3087 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 3088 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 3089 3090 // Helper for demanding the specified elements and all the bits of both binary 3091 // operands. 3092 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 3093 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 3094 TLO.DAG, Depth + 1); 3095 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 3096 TLO.DAG, Depth + 1); 3097 if (NewOp0 || NewOp1) { 3098 SDValue NewOp = 3099 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, 3100 NewOp1 ? NewOp1 : Op1, Op->getFlags()); 3101 return TLO.CombineTo(Op, NewOp); 3102 } 3103 return false; 3104 }; 3105 3106 switch (Opcode) { 3107 case ISD::SCALAR_TO_VECTOR: { 3108 if (!DemandedElts[0]) { 3109 KnownUndef.setAllBits(); 3110 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3111 } 3112 SDValue ScalarSrc = Op.getOperand(0); 3113 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 3114 SDValue Src = ScalarSrc.getOperand(0); 3115 SDValue Idx = ScalarSrc.getOperand(1); 3116 EVT SrcVT = Src.getValueType(); 3117 3118 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 3119 3120 if (SrcEltCnt.isScalable()) 3121 return false; 3122 3123 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 3124 if (isNullConstant(Idx)) { 3125 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 3126 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 3127 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 3128 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3129 TLO, Depth + 1)) 3130 return true; 3131 } 3132 } 3133 KnownUndef.setHighBits(NumElts - 1); 3134 break; 3135 } 3136 case ISD::BITCAST: { 3137 SDValue Src = Op.getOperand(0); 3138 EVT SrcVT = Src.getValueType(); 3139 3140 // We only handle vectors here. 3141 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 3142 if (!SrcVT.isVector()) 3143 break; 3144 3145 // Fast handling of 'identity' bitcasts. 3146 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 3147 if (NumSrcElts == NumElts) 3148 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 3149 KnownZero, TLO, Depth + 1); 3150 3151 APInt SrcDemandedElts, SrcZero, SrcUndef; 3152 3153 // Bitcast from 'large element' src vector to 'small element' vector, we 3154 // must demand a source element if any DemandedElt maps to it. 3155 if ((NumElts % NumSrcElts) == 0) { 3156 unsigned Scale = NumElts / NumSrcElts; 3157 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3158 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3159 TLO, Depth + 1)) 3160 return true; 3161 3162 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 3163 // of the large element. 3164 // TODO - bigendian once we have test coverage. 3165 if (IsLE) { 3166 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 3167 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 3168 for (unsigned i = 0; i != NumElts; ++i) 3169 if (DemandedElts[i]) { 3170 unsigned Ofs = (i % Scale) * EltSizeInBits; 3171 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 3172 } 3173 3174 KnownBits Known; 3175 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 3176 TLO, Depth + 1)) 3177 return true; 3178 3179 // The bitcast has split each wide element into a number of 3180 // narrow subelements. We have just computed the Known bits 3181 // for wide elements. See if element splitting results in 3182 // some subelements being zero. Only for demanded elements! 3183 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 3184 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 3185 .isAllOnes()) 3186 continue; 3187 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 3188 unsigned Elt = Scale * SrcElt + SubElt; 3189 if (DemandedElts[Elt]) 3190 KnownZero.setBit(Elt); 3191 } 3192 } 3193 } 3194 3195 // If the src element is zero/undef then all the output elements will be - 3196 // only demanded elements are guaranteed to be correct. 3197 for (unsigned i = 0; i != NumSrcElts; ++i) { 3198 if (SrcDemandedElts[i]) { 3199 if (SrcZero[i]) 3200 KnownZero.setBits(i * Scale, (i + 1) * Scale); 3201 if (SrcUndef[i]) 3202 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 3203 } 3204 } 3205 } 3206 3207 // Bitcast from 'small element' src vector to 'large element' vector, we 3208 // demand all smaller source elements covered by the larger demanded element 3209 // of this vector. 3210 if ((NumSrcElts % NumElts) == 0) { 3211 unsigned Scale = NumSrcElts / NumElts; 3212 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3213 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3214 TLO, Depth + 1)) 3215 return true; 3216 3217 // If all the src elements covering an output element are zero/undef, then 3218 // the output element will be as well, assuming it was demanded. 3219 for (unsigned i = 0; i != NumElts; ++i) { 3220 if (DemandedElts[i]) { 3221 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 3222 KnownZero.setBit(i); 3223 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 3224 KnownUndef.setBit(i); 3225 } 3226 } 3227 } 3228 break; 3229 } 3230 case ISD::FREEZE: { 3231 SDValue N0 = Op.getOperand(0); 3232 if (TLO.DAG.isGuaranteedNotToBeUndefOrPoison(N0, DemandedElts, 3233 /*PoisonOnly=*/false)) 3234 return TLO.CombineTo(Op, N0); 3235 3236 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE 3237 // freeze(op(x, ...)) -> op(freeze(x), ...). 3238 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) 3239 return TLO.CombineTo( 3240 Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, 3241 TLO.DAG.getFreeze(N0.getOperand(0)))); 3242 break; 3243 } 3244 case ISD::BUILD_VECTOR: { 3245 // Check all elements and simplify any unused elements with UNDEF. 3246 if (!DemandedElts.isAllOnes()) { 3247 // Don't simplify BROADCASTS. 3248 if (llvm::any_of(Op->op_values(), 3249 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 3250 SmallVector<SDValue, 32> Ops(Op->ops()); 3251 bool Updated = false; 3252 for (unsigned i = 0; i != NumElts; ++i) { 3253 if (!DemandedElts[i] && !Ops[i].isUndef()) { 3254 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 3255 KnownUndef.setBit(i); 3256 Updated = true; 3257 } 3258 } 3259 if (Updated) 3260 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 3261 } 3262 } 3263 for (unsigned i = 0; i != NumElts; ++i) { 3264 SDValue SrcOp = Op.getOperand(i); 3265 if (SrcOp.isUndef()) { 3266 KnownUndef.setBit(i); 3267 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 3268 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 3269 KnownZero.setBit(i); 3270 } 3271 } 3272 break; 3273 } 3274 case ISD::CONCAT_VECTORS: { 3275 EVT SubVT = Op.getOperand(0).getValueType(); 3276 unsigned NumSubVecs = Op.getNumOperands(); 3277 unsigned NumSubElts = SubVT.getVectorNumElements(); 3278 for (unsigned i = 0; i != NumSubVecs; ++i) { 3279 SDValue SubOp = Op.getOperand(i); 3280 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3281 APInt SubUndef, SubZero; 3282 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 3283 Depth + 1)) 3284 return true; 3285 KnownUndef.insertBits(SubUndef, i * NumSubElts); 3286 KnownZero.insertBits(SubZero, i * NumSubElts); 3287 } 3288 3289 // Attempt to avoid multi-use ops if we don't need anything from them. 3290 if (!DemandedElts.isAllOnes()) { 3291 bool FoundNewSub = false; 3292 SmallVector<SDValue, 2> DemandedSubOps; 3293 for (unsigned i = 0; i != NumSubVecs; ++i) { 3294 SDValue SubOp = Op.getOperand(i); 3295 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3296 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 3297 SubOp, SubElts, TLO.DAG, Depth + 1); 3298 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 3299 FoundNewSub = NewSubOp ? true : FoundNewSub; 3300 } 3301 if (FoundNewSub) { 3302 SDValue NewOp = 3303 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 3304 return TLO.CombineTo(Op, NewOp); 3305 } 3306 } 3307 break; 3308 } 3309 case ISD::INSERT_SUBVECTOR: { 3310 // Demand any elements from the subvector and the remainder from the src its 3311 // inserted into. 3312 SDValue Src = Op.getOperand(0); 3313 SDValue Sub = Op.getOperand(1); 3314 uint64_t Idx = Op.getConstantOperandVal(2); 3315 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3316 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3317 APInt DemandedSrcElts = DemandedElts; 3318 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3319 3320 APInt SubUndef, SubZero; 3321 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 3322 Depth + 1)) 3323 return true; 3324 3325 // If none of the src operand elements are demanded, replace it with undef. 3326 if (!DemandedSrcElts && !Src.isUndef()) 3327 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 3328 TLO.DAG.getUNDEF(VT), Sub, 3329 Op.getOperand(2))); 3330 3331 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 3332 TLO, Depth + 1)) 3333 return true; 3334 KnownUndef.insertBits(SubUndef, Idx); 3335 KnownZero.insertBits(SubZero, Idx); 3336 3337 // Attempt to avoid multi-use ops if we don't need anything from them. 3338 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3339 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3340 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3341 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3342 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3343 if (NewSrc || NewSub) { 3344 NewSrc = NewSrc ? NewSrc : Src; 3345 NewSub = NewSub ? NewSub : Sub; 3346 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3347 NewSub, Op.getOperand(2)); 3348 return TLO.CombineTo(Op, NewOp); 3349 } 3350 } 3351 break; 3352 } 3353 case ISD::EXTRACT_SUBVECTOR: { 3354 // Offset the demanded elts by the subvector index. 3355 SDValue Src = Op.getOperand(0); 3356 if (Src.getValueType().isScalableVector()) 3357 break; 3358 uint64_t Idx = Op.getConstantOperandVal(1); 3359 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3360 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3361 3362 APInt SrcUndef, SrcZero; 3363 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3364 Depth + 1)) 3365 return true; 3366 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3367 KnownZero = SrcZero.extractBits(NumElts, Idx); 3368 3369 // Attempt to avoid multi-use ops if we don't need anything from them. 3370 if (!DemandedElts.isAllOnes()) { 3371 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3372 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3373 if (NewSrc) { 3374 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3375 Op.getOperand(1)); 3376 return TLO.CombineTo(Op, NewOp); 3377 } 3378 } 3379 break; 3380 } 3381 case ISD::INSERT_VECTOR_ELT: { 3382 SDValue Vec = Op.getOperand(0); 3383 SDValue Scl = Op.getOperand(1); 3384 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3385 3386 // For a legal, constant insertion index, if we don't need this insertion 3387 // then strip it, else remove it from the demanded elts. 3388 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3389 unsigned Idx = CIdx->getZExtValue(); 3390 if (!DemandedElts[Idx]) 3391 return TLO.CombineTo(Op, Vec); 3392 3393 APInt DemandedVecElts(DemandedElts); 3394 DemandedVecElts.clearBit(Idx); 3395 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3396 KnownZero, TLO, Depth + 1)) 3397 return true; 3398 3399 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3400 3401 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3402 break; 3403 } 3404 3405 APInt VecUndef, VecZero; 3406 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3407 Depth + 1)) 3408 return true; 3409 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3410 break; 3411 } 3412 case ISD::VSELECT: { 3413 SDValue Sel = Op.getOperand(0); 3414 SDValue LHS = Op.getOperand(1); 3415 SDValue RHS = Op.getOperand(2); 3416 3417 // Try to transform the select condition based on the current demanded 3418 // elements. 3419 APInt UndefSel, ZeroSel; 3420 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO, 3421 Depth + 1)) 3422 return true; 3423 3424 // See if we can simplify either vselect operand. 3425 APInt DemandedLHS(DemandedElts); 3426 APInt DemandedRHS(DemandedElts); 3427 APInt UndefLHS, ZeroLHS; 3428 APInt UndefRHS, ZeroRHS; 3429 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3430 Depth + 1)) 3431 return true; 3432 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3433 Depth + 1)) 3434 return true; 3435 3436 KnownUndef = UndefLHS & UndefRHS; 3437 KnownZero = ZeroLHS & ZeroRHS; 3438 3439 // If we know that the selected element is always zero, we don't need the 3440 // select value element. 3441 APInt DemandedSel = DemandedElts & ~KnownZero; 3442 if (DemandedSel != DemandedElts) 3443 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO, 3444 Depth + 1)) 3445 return true; 3446 3447 break; 3448 } 3449 case ISD::VECTOR_SHUFFLE: { 3450 SDValue LHS = Op.getOperand(0); 3451 SDValue RHS = Op.getOperand(1); 3452 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3453 3454 // Collect demanded elements from shuffle operands.. 3455 APInt DemandedLHS(NumElts, 0); 3456 APInt DemandedRHS(NumElts, 0); 3457 for (unsigned i = 0; i != NumElts; ++i) { 3458 int M = ShuffleMask[i]; 3459 if (M < 0 || !DemandedElts[i]) 3460 continue; 3461 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3462 if (M < (int)NumElts) 3463 DemandedLHS.setBit(M); 3464 else 3465 DemandedRHS.setBit(M - NumElts); 3466 } 3467 3468 // See if we can simplify either shuffle operand. 3469 APInt UndefLHS, ZeroLHS; 3470 APInt UndefRHS, ZeroRHS; 3471 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3472 Depth + 1)) 3473 return true; 3474 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3475 Depth + 1)) 3476 return true; 3477 3478 // Simplify mask using undef elements from LHS/RHS. 3479 bool Updated = false; 3480 bool IdentityLHS = true, IdentityRHS = true; 3481 SmallVector<int, 32> NewMask(ShuffleMask); 3482 for (unsigned i = 0; i != NumElts; ++i) { 3483 int &M = NewMask[i]; 3484 if (M < 0) 3485 continue; 3486 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3487 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3488 Updated = true; 3489 M = -1; 3490 } 3491 IdentityLHS &= (M < 0) || (M == (int)i); 3492 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3493 } 3494 3495 // Update legal shuffle masks based on demanded elements if it won't reduce 3496 // to Identity which can cause premature removal of the shuffle mask. 3497 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3498 SDValue LegalShuffle = 3499 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG); 3500 if (LegalShuffle) 3501 return TLO.CombineTo(Op, LegalShuffle); 3502 } 3503 3504 // Propagate undef/zero elements from LHS/RHS. 3505 for (unsigned i = 0; i != NumElts; ++i) { 3506 int M = ShuffleMask[i]; 3507 if (M < 0) { 3508 KnownUndef.setBit(i); 3509 } else if (M < (int)NumElts) { 3510 if (UndefLHS[M]) 3511 KnownUndef.setBit(i); 3512 if (ZeroLHS[M]) 3513 KnownZero.setBit(i); 3514 } else { 3515 if (UndefRHS[M - NumElts]) 3516 KnownUndef.setBit(i); 3517 if (ZeroRHS[M - NumElts]) 3518 KnownZero.setBit(i); 3519 } 3520 } 3521 break; 3522 } 3523 case ISD::ANY_EXTEND_VECTOR_INREG: 3524 case ISD::SIGN_EXTEND_VECTOR_INREG: 3525 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3526 APInt SrcUndef, SrcZero; 3527 SDValue Src = Op.getOperand(0); 3528 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3529 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3530 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3531 Depth + 1)) 3532 return true; 3533 KnownZero = SrcZero.zextOrTrunc(NumElts); 3534 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3535 3536 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3537 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3538 DemandedSrcElts == 1) { 3539 // aext - if we just need the bottom element then we can bitcast. 3540 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3541 } 3542 3543 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3544 // zext(undef) upper bits are guaranteed to be zero. 3545 if (DemandedElts.isSubsetOf(KnownUndef)) 3546 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3547 KnownUndef.clearAllBits(); 3548 3549 // zext - if we just need the bottom element then we can mask: 3550 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3551 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3552 Op->isOnlyUserOf(Src.getNode()) && 3553 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3554 SDLoc DL(Op); 3555 EVT SrcVT = Src.getValueType(); 3556 EVT SrcSVT = SrcVT.getScalarType(); 3557 SmallVector<SDValue> MaskElts; 3558 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3559 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3560 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3561 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3562 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3563 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3564 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3565 } 3566 } 3567 } 3568 break; 3569 } 3570 3571 // TODO: There are more binop opcodes that could be handled here - MIN, 3572 // MAX, saturated math, etc. 3573 case ISD::ADD: { 3574 SDValue Op0 = Op.getOperand(0); 3575 SDValue Op1 = Op.getOperand(1); 3576 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3577 APInt UndefLHS, ZeroLHS; 3578 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3579 Depth + 1, /*AssumeSingleUse*/ true)) 3580 return true; 3581 } 3582 [[fallthrough]]; 3583 } 3584 case ISD::AVGCEILS: 3585 case ISD::AVGCEILU: 3586 case ISD::AVGFLOORS: 3587 case ISD::AVGFLOORU: 3588 case ISD::OR: 3589 case ISD::XOR: 3590 case ISD::SUB: 3591 case ISD::FADD: 3592 case ISD::FSUB: 3593 case ISD::FMUL: 3594 case ISD::FDIV: 3595 case ISD::FREM: { 3596 SDValue Op0 = Op.getOperand(0); 3597 SDValue Op1 = Op.getOperand(1); 3598 3599 APInt UndefRHS, ZeroRHS; 3600 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3601 Depth + 1)) 3602 return true; 3603 APInt UndefLHS, ZeroLHS; 3604 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3605 Depth + 1)) 3606 return true; 3607 3608 KnownZero = ZeroLHS & ZeroRHS; 3609 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3610 3611 // Attempt to avoid multi-use ops if we don't need anything from them. 3612 // TODO - use KnownUndef to relax the demandedelts? 3613 if (!DemandedElts.isAllOnes()) 3614 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3615 return true; 3616 break; 3617 } 3618 case ISD::SHL: 3619 case ISD::SRL: 3620 case ISD::SRA: 3621 case ISD::ROTL: 3622 case ISD::ROTR: { 3623 SDValue Op0 = Op.getOperand(0); 3624 SDValue Op1 = Op.getOperand(1); 3625 3626 APInt UndefRHS, ZeroRHS; 3627 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3628 Depth + 1)) 3629 return true; 3630 APInt UndefLHS, ZeroLHS; 3631 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3632 Depth + 1)) 3633 return true; 3634 3635 KnownZero = ZeroLHS; 3636 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3637 3638 // Attempt to avoid multi-use ops if we don't need anything from them. 3639 // TODO - use KnownUndef to relax the demandedelts? 3640 if (!DemandedElts.isAllOnes()) 3641 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3642 return true; 3643 break; 3644 } 3645 case ISD::MUL: 3646 case ISD::MULHU: 3647 case ISD::MULHS: 3648 case ISD::AND: { 3649 SDValue Op0 = Op.getOperand(0); 3650 SDValue Op1 = Op.getOperand(1); 3651 3652 APInt SrcUndef, SrcZero; 3653 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3654 Depth + 1)) 3655 return true; 3656 // If we know that a demanded element was zero in Op1 we don't need to 3657 // demand it in Op0 - its guaranteed to be zero. 3658 APInt DemandedElts0 = DemandedElts & ~SrcZero; 3659 if (SimplifyDemandedVectorElts(Op0, DemandedElts0, KnownUndef, KnownZero, 3660 TLO, Depth + 1)) 3661 return true; 3662 3663 KnownUndef &= DemandedElts0; 3664 KnownZero &= DemandedElts0; 3665 3666 // If every element pair has a zero/undef then just fold to zero. 3667 // fold (and x, undef) -> 0 / (and x, 0) -> 0 3668 // fold (mul x, undef) -> 0 / (mul x, 0) -> 0 3669 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef)) 3670 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3671 3672 // If either side has a zero element, then the result element is zero, even 3673 // if the other is an UNDEF. 3674 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3675 // and then handle 'and' nodes with the rest of the binop opcodes. 3676 KnownZero |= SrcZero; 3677 KnownUndef &= SrcUndef; 3678 KnownUndef &= ~KnownZero; 3679 3680 // Attempt to avoid multi-use ops if we don't need anything from them. 3681 if (!DemandedElts.isAllOnes()) 3682 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3683 return true; 3684 break; 3685 } 3686 case ISD::TRUNCATE: 3687 case ISD::SIGN_EXTEND: 3688 case ISD::ZERO_EXTEND: 3689 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3690 KnownZero, TLO, Depth + 1)) 3691 return true; 3692 3693 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3694 // zext(undef) upper bits are guaranteed to be zero. 3695 if (DemandedElts.isSubsetOf(KnownUndef)) 3696 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3697 KnownUndef.clearAllBits(); 3698 } 3699 break; 3700 default: { 3701 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3702 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3703 KnownZero, TLO, Depth)) 3704 return true; 3705 } else { 3706 KnownBits Known; 3707 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3708 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3709 TLO, Depth, AssumeSingleUse)) 3710 return true; 3711 } 3712 break; 3713 } 3714 } 3715 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3716 3717 // Constant fold all undef cases. 3718 // TODO: Handle zero cases as well. 3719 if (DemandedElts.isSubsetOf(KnownUndef)) 3720 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3721 3722 return false; 3723 } 3724 3725 /// Determine which of the bits specified in Mask are known to be either zero or 3726 /// one and return them in the Known. 3727 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3728 KnownBits &Known, 3729 const APInt &DemandedElts, 3730 const SelectionDAG &DAG, 3731 unsigned Depth) const { 3732 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3733 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3734 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3735 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3736 "Should use MaskedValueIsZero if you don't know whether Op" 3737 " is a target node!"); 3738 Known.resetAll(); 3739 } 3740 3741 void TargetLowering::computeKnownBitsForTargetInstr( 3742 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3743 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3744 unsigned Depth) const { 3745 Known.resetAll(); 3746 } 3747 3748 void TargetLowering::computeKnownBitsForFrameIndex( 3749 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3750 // The low bits are known zero if the pointer is aligned. 3751 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3752 } 3753 3754 Align TargetLowering::computeKnownAlignForTargetInstr( 3755 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3756 unsigned Depth) const { 3757 return Align(1); 3758 } 3759 3760 /// This method can be implemented by targets that want to expose additional 3761 /// information about sign bits to the DAG Combiner. 3762 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3763 const APInt &, 3764 const SelectionDAG &, 3765 unsigned Depth) const { 3766 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3767 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3768 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3769 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3770 "Should use ComputeNumSignBits if you don't know whether Op" 3771 " is a target node!"); 3772 return 1; 3773 } 3774 3775 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3776 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3777 const MachineRegisterInfo &MRI, unsigned Depth) const { 3778 return 1; 3779 } 3780 3781 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3782 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3783 TargetLoweringOpt &TLO, unsigned Depth) const { 3784 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3785 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3786 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3787 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3788 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3789 " is a target node!"); 3790 return false; 3791 } 3792 3793 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3794 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3795 KnownBits &Known, TargetLoweringOpt &TLO, 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 SimplifyDemandedBits if you don't know whether Op" 3801 " is a target node!"); 3802 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3803 return false; 3804 } 3805 3806 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3807 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3808 SelectionDAG &DAG, unsigned Depth) const { 3809 assert( 3810 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3811 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3812 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3813 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3814 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3815 " is a target node!"); 3816 return SDValue(); 3817 } 3818 3819 SDValue 3820 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3821 SDValue N1, MutableArrayRef<int> Mask, 3822 SelectionDAG &DAG) const { 3823 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3824 if (!LegalMask) { 3825 std::swap(N0, N1); 3826 ShuffleVectorSDNode::commuteMask(Mask); 3827 LegalMask = isShuffleMaskLegal(Mask, VT); 3828 } 3829 3830 if (!LegalMask) 3831 return SDValue(); 3832 3833 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3834 } 3835 3836 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3837 return nullptr; 3838 } 3839 3840 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3841 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3842 bool PoisonOnly, unsigned Depth) const { 3843 assert( 3844 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3845 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3846 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3847 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3848 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3849 " is a target node!"); 3850 3851 // If Op can't create undef/poison and none of its operands are undef/poison 3852 // then Op is never undef/poison. 3853 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, PoisonOnly, 3854 /*ConsiderFlags*/ true, Depth) && 3855 all_of(Op->ops(), [&](SDValue V) { 3856 return DAG.isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, 3857 Depth + 1); 3858 }); 3859 } 3860 3861 bool TargetLowering::canCreateUndefOrPoisonForTargetNode( 3862 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3863 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const { 3864 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3865 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3866 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3867 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3868 "Should use canCreateUndefOrPoison if you don't know whether Op" 3869 " is a target node!"); 3870 // Be conservative and return true. 3871 return true; 3872 } 3873 3874 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3875 const SelectionDAG &DAG, 3876 bool SNaN, 3877 unsigned Depth) const { 3878 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3879 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3880 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3881 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3882 "Should use isKnownNeverNaN if you don't know whether Op" 3883 " is a target node!"); 3884 return false; 3885 } 3886 3887 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3888 const APInt &DemandedElts, 3889 APInt &UndefElts, 3890 const SelectionDAG &DAG, 3891 unsigned Depth) const { 3892 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3893 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3894 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3895 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3896 "Should use isSplatValue if you don't know whether Op" 3897 " is a target node!"); 3898 return false; 3899 } 3900 3901 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3902 // work with truncating build vectors and vectors with elements of less than 3903 // 8 bits. 3904 bool TargetLowering::isConstTrueVal(SDValue N) const { 3905 if (!N) 3906 return false; 3907 3908 unsigned EltWidth; 3909 APInt CVal; 3910 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3911 /*AllowTruncation=*/true)) { 3912 CVal = CN->getAPIntValue(); 3913 EltWidth = N.getValueType().getScalarSizeInBits(); 3914 } else 3915 return false; 3916 3917 // If this is a truncating splat, truncate the splat value. 3918 // Otherwise, we may fail to match the expected values below. 3919 if (EltWidth < CVal.getBitWidth()) 3920 CVal = CVal.trunc(EltWidth); 3921 3922 switch (getBooleanContents(N.getValueType())) { 3923 case UndefinedBooleanContent: 3924 return CVal[0]; 3925 case ZeroOrOneBooleanContent: 3926 return CVal.isOne(); 3927 case ZeroOrNegativeOneBooleanContent: 3928 return CVal.isAllOnes(); 3929 } 3930 3931 llvm_unreachable("Invalid boolean contents"); 3932 } 3933 3934 bool TargetLowering::isConstFalseVal(SDValue N) const { 3935 if (!N) 3936 return false; 3937 3938 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3939 if (!CN) { 3940 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3941 if (!BV) 3942 return false; 3943 3944 // Only interested in constant splats, we don't care about undef 3945 // elements in identifying boolean constants and getConstantSplatNode 3946 // returns NULL if all ops are undef; 3947 CN = BV->getConstantSplatNode(); 3948 if (!CN) 3949 return false; 3950 } 3951 3952 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3953 return !CN->getAPIntValue()[0]; 3954 3955 return CN->isZero(); 3956 } 3957 3958 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3959 bool SExt) const { 3960 if (VT == MVT::i1) 3961 return N->isOne(); 3962 3963 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3964 switch (Cnt) { 3965 case TargetLowering::ZeroOrOneBooleanContent: 3966 // An extended value of 1 is always true, unless its original type is i1, 3967 // in which case it will be sign extended to -1. 3968 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3969 case TargetLowering::UndefinedBooleanContent: 3970 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3971 return N->isAllOnes() && SExt; 3972 } 3973 llvm_unreachable("Unexpected enumeration."); 3974 } 3975 3976 /// This helper function of SimplifySetCC tries to optimize the comparison when 3977 /// either operand of the SetCC node is a bitwise-and instruction. 3978 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3979 ISD::CondCode Cond, const SDLoc &DL, 3980 DAGCombinerInfo &DCI) const { 3981 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3982 std::swap(N0, N1); 3983 3984 SelectionDAG &DAG = DCI.DAG; 3985 EVT OpVT = N0.getValueType(); 3986 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3987 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3988 return SDValue(); 3989 3990 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3991 // iff everything but LSB is known zero: 3992 if (Cond == ISD::SETNE && isNullConstant(N1) && 3993 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3994 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3995 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3996 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3997 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3998 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3999 } 4000 4001 // Try to eliminate a power-of-2 mask constant by converting to a signbit 4002 // test in a narrow type that we can truncate to with no cost. Examples: 4003 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0 4004 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0 4005 // TODO: This conservatively checks for type legality on the source and 4006 // destination types. That may inhibit optimizations, but it also 4007 // allows setcc->shift transforms that may be more beneficial. 4008 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4009 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() && 4010 isTypeLegal(OpVT) && N0.hasOneUse()) { 4011 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), 4012 AndC->getAPIntValue().getActiveBits()); 4013 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) { 4014 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT); 4015 SDValue Zero = DAG.getConstant(0, DL, NarrowVT); 4016 return DAG.getSetCC(DL, VT, Trunc, Zero, 4017 Cond == ISD::SETEQ ? ISD::SETGE : ISD::SETLT); 4018 } 4019 } 4020 4021 // Match these patterns in any of their permutations: 4022 // (X & Y) == Y 4023 // (X & Y) != Y 4024 SDValue X, Y; 4025 if (N0.getOperand(0) == N1) { 4026 X = N0.getOperand(1); 4027 Y = N0.getOperand(0); 4028 } else if (N0.getOperand(1) == N1) { 4029 X = N0.getOperand(0); 4030 Y = N0.getOperand(1); 4031 } else { 4032 return SDValue(); 4033 } 4034 4035 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if 4036 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as 4037 // its liable to create and infinite loop. 4038 SDValue Zero = DAG.getConstant(0, DL, OpVT); 4039 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) && 4040 DAG.isKnownToBeAPowerOfTwo(Y)) { 4041 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 4042 // Note that where Y is variable and is known to have at most one bit set 4043 // (for example, if it is Z & 1) we cannot do this; the expressions are not 4044 // equivalent when Y == 0. 4045 assert(OpVT.isInteger()); 4046 Cond = ISD::getSetCCInverse(Cond, OpVT); 4047 if (DCI.isBeforeLegalizeOps() || 4048 isCondCodeLegal(Cond, N0.getSimpleValueType())) 4049 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 4050 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 4051 // If the target supports an 'and-not' or 'and-complement' logic operation, 4052 // try to use that to make a comparison operation more efficient. 4053 // But don't do this transform if the mask is a single bit because there are 4054 // more efficient ways to deal with that case (for example, 'bt' on x86 or 4055 // 'rlwinm' on PPC). 4056 4057 // Bail out if the compare operand that we want to turn into a zero is 4058 // already a zero (otherwise, infinite loop). 4059 if (isNullConstant(Y)) 4060 return SDValue(); 4061 4062 // Transform this into: ~X & Y == 0. 4063 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 4064 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 4065 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 4066 } 4067 4068 return SDValue(); 4069 } 4070 4071 /// There are multiple IR patterns that could be checking whether certain 4072 /// truncation of a signed number would be lossy or not. The pattern which is 4073 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 4074 /// We are looking for the following pattern: (KeptBits is a constant) 4075 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 4076 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 4077 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 4078 /// We will unfold it into the natural trunc+sext pattern: 4079 /// ((%x << C) a>> C) dstcond %x 4080 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 4081 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 4082 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 4083 const SDLoc &DL) const { 4084 // We must be comparing with a constant. 4085 ConstantSDNode *C1; 4086 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 4087 return SDValue(); 4088 4089 // N0 should be: add %x, (1 << (KeptBits-1)) 4090 if (N0->getOpcode() != ISD::ADD) 4091 return SDValue(); 4092 4093 // And we must be 'add'ing a constant. 4094 ConstantSDNode *C01; 4095 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 4096 return SDValue(); 4097 4098 SDValue X = N0->getOperand(0); 4099 EVT XVT = X.getValueType(); 4100 4101 // Validate constants ... 4102 4103 APInt I1 = C1->getAPIntValue(); 4104 4105 ISD::CondCode NewCond; 4106 if (Cond == ISD::CondCode::SETULT) { 4107 NewCond = ISD::CondCode::SETEQ; 4108 } else if (Cond == ISD::CondCode::SETULE) { 4109 NewCond = ISD::CondCode::SETEQ; 4110 // But need to 'canonicalize' the constant. 4111 I1 += 1; 4112 } else if (Cond == ISD::CondCode::SETUGT) { 4113 NewCond = ISD::CondCode::SETNE; 4114 // But need to 'canonicalize' the constant. 4115 I1 += 1; 4116 } else if (Cond == ISD::CondCode::SETUGE) { 4117 NewCond = ISD::CondCode::SETNE; 4118 } else 4119 return SDValue(); 4120 4121 APInt I01 = C01->getAPIntValue(); 4122 4123 auto checkConstants = [&I1, &I01]() -> bool { 4124 // Both of them must be power-of-two, and the constant from setcc is bigger. 4125 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 4126 }; 4127 4128 if (checkConstants()) { 4129 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 4130 } else { 4131 // What if we invert constants? (and the target predicate) 4132 I1.negate(); 4133 I01.negate(); 4134 assert(XVT.isInteger()); 4135 NewCond = getSetCCInverse(NewCond, XVT); 4136 if (!checkConstants()) 4137 return SDValue(); 4138 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 4139 } 4140 4141 // They are power-of-two, so which bit is set? 4142 const unsigned KeptBits = I1.logBase2(); 4143 const unsigned KeptBitsMinusOne = I01.logBase2(); 4144 4145 // Magic! 4146 if (KeptBits != (KeptBitsMinusOne + 1)) 4147 return SDValue(); 4148 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 4149 4150 // We don't want to do this in every single case. 4151 SelectionDAG &DAG = DCI.DAG; 4152 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits)) 4153 return SDValue(); 4154 4155 // Unfold into: sext_inreg(%x) cond %x 4156 // Where 'cond' will be either 'eq' or 'ne'. 4157 SDValue SExtInReg = DAG.getNode( 4158 ISD::SIGN_EXTEND_INREG, DL, XVT, X, 4159 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits))); 4160 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond); 4161 } 4162 4163 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4164 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 4165 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 4166 DAGCombinerInfo &DCI, const SDLoc &DL) const { 4167 assert(isConstOrConstSplat(N1C) && isConstOrConstSplat(N1C)->isZero() && 4168 "Should be a comparison with 0."); 4169 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4170 "Valid only for [in]equality comparisons."); 4171 4172 unsigned NewShiftOpcode; 4173 SDValue X, C, Y; 4174 4175 SelectionDAG &DAG = DCI.DAG; 4176 4177 // Look for '(C l>>/<< Y)'. 4178 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) { 4179 // The shift should be one-use. 4180 if (!V.hasOneUse()) 4181 return false; 4182 unsigned OldShiftOpcode = V.getOpcode(); 4183 switch (OldShiftOpcode) { 4184 case ISD::SHL: 4185 NewShiftOpcode = ISD::SRL; 4186 break; 4187 case ISD::SRL: 4188 NewShiftOpcode = ISD::SHL; 4189 break; 4190 default: 4191 return false; // must be a logical shift. 4192 } 4193 // We should be shifting a constant. 4194 // FIXME: best to use isConstantOrConstantVector(). 4195 C = V.getOperand(0); 4196 ConstantSDNode *CC = 4197 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4198 if (!CC) 4199 return false; 4200 Y = V.getOperand(1); 4201 4202 ConstantSDNode *XC = 4203 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4204 return shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 4205 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 4206 }; 4207 4208 // LHS of comparison should be an one-use 'and'. 4209 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 4210 return SDValue(); 4211 4212 X = N0.getOperand(0); 4213 SDValue Mask = N0.getOperand(1); 4214 4215 // 'and' is commutative! 4216 if (!Match(Mask)) { 4217 std::swap(X, Mask); 4218 if (!Match(Mask)) 4219 return SDValue(); 4220 } 4221 4222 EVT VT = X.getValueType(); 4223 4224 // Produce: 4225 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 4226 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 4227 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 4228 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 4229 return T2; 4230 } 4231 4232 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 4233 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 4234 /// handle the commuted versions of these patterns. 4235 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 4236 ISD::CondCode Cond, const SDLoc &DL, 4237 DAGCombinerInfo &DCI) const { 4238 unsigned BOpcode = N0.getOpcode(); 4239 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 4240 "Unexpected binop"); 4241 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 4242 4243 // (X + Y) == X --> Y == 0 4244 // (X - Y) == X --> Y == 0 4245 // (X ^ Y) == X --> Y == 0 4246 SelectionDAG &DAG = DCI.DAG; 4247 EVT OpVT = N0.getValueType(); 4248 SDValue X = N0.getOperand(0); 4249 SDValue Y = N0.getOperand(1); 4250 if (X == N1) 4251 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 4252 4253 if (Y != N1) 4254 return SDValue(); 4255 4256 // (X + Y) == Y --> X == 0 4257 // (X ^ Y) == Y --> X == 0 4258 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 4259 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 4260 4261 // The shift would not be valid if the operands are boolean (i1). 4262 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 4263 return SDValue(); 4264 4265 // (X - Y) == Y --> X == Y << 1 4266 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL); 4267 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 4268 if (!DCI.isCalledByLegalizer()) 4269 DCI.AddToWorklist(YShl1.getNode()); 4270 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 4271 } 4272 4273 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 4274 SDValue N0, const APInt &C1, 4275 ISD::CondCode Cond, const SDLoc &dl, 4276 SelectionDAG &DAG) { 4277 // Look through truncs that don't change the value of a ctpop. 4278 // FIXME: Add vector support? Need to be careful with setcc result type below. 4279 SDValue CTPOP = N0; 4280 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 4281 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 4282 CTPOP = N0.getOperand(0); 4283 4284 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 4285 return SDValue(); 4286 4287 EVT CTVT = CTPOP.getValueType(); 4288 SDValue CTOp = CTPOP.getOperand(0); 4289 4290 // Expand a power-of-2-or-zero comparison based on ctpop: 4291 // (ctpop x) u< 2 -> (x & x-1) == 0 4292 // (ctpop x) u> 1 -> (x & x-1) != 0 4293 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 4294 // Keep the CTPOP if it is a cheap vector op. 4295 if (CTVT.isVector() && TLI.isCtpopFast(CTVT)) 4296 return SDValue(); 4297 4298 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 4299 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 4300 return SDValue(); 4301 if (C1 == 0 && (Cond == ISD::SETULT)) 4302 return SDValue(); // This is handled elsewhere. 4303 4304 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 4305 4306 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4307 SDValue Result = CTOp; 4308 for (unsigned i = 0; i < Passes; i++) { 4309 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 4310 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 4311 } 4312 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 4313 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 4314 } 4315 4316 // Expand a power-of-2 comparison based on ctpop 4317 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 4318 // Keep the CTPOP if it is cheap. 4319 if (TLI.isCtpopFast(CTVT)) 4320 return SDValue(); 4321 4322 SDValue Zero = DAG.getConstant(0, dl, CTVT); 4323 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4324 assert(CTVT.isInteger()); 4325 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 4326 4327 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so 4328 // check before emitting a potentially unnecessary op. 4329 if (DAG.isKnownNeverZero(CTOp)) { 4330 // (ctpop x) == 1 --> (x & x-1) == 0 4331 // (ctpop x) != 1 --> (x & x-1) != 0 4332 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 4333 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 4334 return RHS; 4335 } 4336 4337 // (ctpop x) == 1 --> (x ^ x-1) > x-1 4338 // (ctpop x) != 1 --> (x ^ x-1) <= x-1 4339 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add); 4340 ISD::CondCode CmpCond = Cond == ISD::SETEQ ? ISD::SETUGT : ISD::SETULE; 4341 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond); 4342 } 4343 4344 return SDValue(); 4345 } 4346 4347 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 4348 ISD::CondCode Cond, const SDLoc &dl, 4349 SelectionDAG &DAG) { 4350 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4351 return SDValue(); 4352 4353 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4354 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 4355 return SDValue(); 4356 4357 auto getRotateSource = [](SDValue X) { 4358 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 4359 return X.getOperand(0); 4360 return SDValue(); 4361 }; 4362 4363 // Peek through a rotated value compared against 0 or -1: 4364 // (rot X, Y) == 0/-1 --> X == 0/-1 4365 // (rot X, Y) != 0/-1 --> X != 0/-1 4366 if (SDValue R = getRotateSource(N0)) 4367 return DAG.getSetCC(dl, VT, R, N1, Cond); 4368 4369 // Peek through an 'or' of a rotated value compared against 0: 4370 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 4371 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 4372 // 4373 // TODO: Add the 'and' with -1 sibling. 4374 // TODO: Recurse through a series of 'or' ops to find the rotate. 4375 EVT OpVT = N0.getValueType(); 4376 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 4377 if (SDValue R = getRotateSource(N0.getOperand(0))) { 4378 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 4379 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4380 } 4381 if (SDValue R = getRotateSource(N0.getOperand(1))) { 4382 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 4383 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4384 } 4385 } 4386 4387 return SDValue(); 4388 } 4389 4390 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 4391 ISD::CondCode Cond, const SDLoc &dl, 4392 SelectionDAG &DAG) { 4393 // If we are testing for all-bits-clear, we might be able to do that with 4394 // less shifting since bit-order does not matter. 4395 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4396 return SDValue(); 4397 4398 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4399 if (!C1 || !C1->isZero()) 4400 return SDValue(); 4401 4402 if (!N0.hasOneUse() || 4403 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4404 return SDValue(); 4405 4406 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4407 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4408 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4409 return SDValue(); 4410 4411 // Canonicalize fshr as fshl to reduce pattern-matching. 4412 unsigned ShAmt = ShAmtC->getZExtValue(); 4413 if (N0.getOpcode() == ISD::FSHR) 4414 ShAmt = BitWidth - ShAmt; 4415 4416 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4417 SDValue X, Y; 4418 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4419 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4420 return false; 4421 if (Or.getOperand(0) == Other) { 4422 X = Or.getOperand(0); 4423 Y = Or.getOperand(1); 4424 return true; 4425 } 4426 if (Or.getOperand(1) == Other) { 4427 X = Or.getOperand(1); 4428 Y = Or.getOperand(0); 4429 return true; 4430 } 4431 return false; 4432 }; 4433 4434 EVT OpVT = N0.getValueType(); 4435 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4436 SDValue F0 = N0.getOperand(0); 4437 SDValue F1 = N0.getOperand(1); 4438 if (matchOr(F0, F1)) { 4439 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4440 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4441 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4442 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4443 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4444 } 4445 if (matchOr(F1, F0)) { 4446 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4447 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4448 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4449 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4450 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4451 } 4452 4453 return SDValue(); 4454 } 4455 4456 /// Try to simplify a setcc built with the specified operands and cc. If it is 4457 /// unable to simplify it, return a null SDValue. 4458 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4459 ISD::CondCode Cond, bool foldBooleans, 4460 DAGCombinerInfo &DCI, 4461 const SDLoc &dl) const { 4462 SelectionDAG &DAG = DCI.DAG; 4463 const DataLayout &Layout = DAG.getDataLayout(); 4464 EVT OpVT = N0.getValueType(); 4465 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4466 4467 // Constant fold or commute setcc. 4468 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4469 return Fold; 4470 4471 bool N0ConstOrSplat = 4472 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4473 bool N1ConstOrSplat = 4474 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4475 4476 // Canonicalize toward having the constant on the RHS. 4477 // TODO: Handle non-splat vector constants. All undef causes trouble. 4478 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4479 // infinite loop here when we encounter one. 4480 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4481 if (N0ConstOrSplat && !N1ConstOrSplat && 4482 (DCI.isBeforeLegalizeOps() || 4483 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4484 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4485 4486 // If we have a subtract with the same 2 non-constant operands as this setcc 4487 // -- but in reverse order -- then try to commute the operands of this setcc 4488 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4489 // instruction on some targets. 4490 if (!N0ConstOrSplat && !N1ConstOrSplat && 4491 (DCI.isBeforeLegalizeOps() || 4492 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4493 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4494 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4495 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4496 4497 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4498 return V; 4499 4500 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4501 return V; 4502 4503 if (auto *N1C = isConstOrConstSplat(N1)) { 4504 const APInt &C1 = N1C->getAPIntValue(); 4505 4506 // Optimize some CTPOP cases. 4507 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4508 return V; 4509 4510 // For equality to 0 of a no-wrap multiply, decompose and test each op: 4511 // X * Y == 0 --> (X == 0) || (Y == 0) 4512 // X * Y != 0 --> (X != 0) && (Y != 0) 4513 // TODO: This bails out if minsize is set, but if the target doesn't have a 4514 // single instruction multiply for this type, it would likely be 4515 // smaller to decompose. 4516 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4517 N0.getOpcode() == ISD::MUL && N0.hasOneUse() && 4518 (N0->getFlags().hasNoUnsignedWrap() || 4519 N0->getFlags().hasNoSignedWrap()) && 4520 !Attr.hasFnAttr(Attribute::MinSize)) { 4521 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4522 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond); 4523 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND; 4524 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero); 4525 } 4526 4527 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4528 // equality comparison, then we're just comparing whether X itself is 4529 // zero. 4530 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4531 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4532 llvm::has_single_bit<uint32_t>(N0.getScalarValueSizeInBits())) { 4533 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4534 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4535 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4536 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4537 // (srl (ctlz x), 5) == 0 -> X != 0 4538 // (srl (ctlz x), 5) != 1 -> X != 0 4539 Cond = ISD::SETNE; 4540 } else { 4541 // (srl (ctlz x), 5) != 0 -> X == 0 4542 // (srl (ctlz x), 5) == 1 -> X == 0 4543 Cond = ISD::SETEQ; 4544 } 4545 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4546 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4547 Cond); 4548 } 4549 } 4550 } 4551 } 4552 4553 // FIXME: Support vectors. 4554 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4555 const APInt &C1 = N1C->getAPIntValue(); 4556 4557 // (zext x) == C --> x == (trunc C) 4558 // (sext x) == C --> x == (trunc C) 4559 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4560 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4561 unsigned MinBits = N0.getValueSizeInBits(); 4562 SDValue PreExt; 4563 bool Signed = false; 4564 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4565 // ZExt 4566 MinBits = N0->getOperand(0).getValueSizeInBits(); 4567 PreExt = N0->getOperand(0); 4568 } else if (N0->getOpcode() == ISD::AND) { 4569 // DAGCombine turns costly ZExts into ANDs 4570 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4571 if ((C->getAPIntValue()+1).isPowerOf2()) { 4572 MinBits = C->getAPIntValue().countr_one(); 4573 PreExt = N0->getOperand(0); 4574 } 4575 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4576 // SExt 4577 MinBits = N0->getOperand(0).getValueSizeInBits(); 4578 PreExt = N0->getOperand(0); 4579 Signed = true; 4580 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4581 // ZEXTLOAD / SEXTLOAD 4582 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4583 MinBits = LN0->getMemoryVT().getSizeInBits(); 4584 PreExt = N0; 4585 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4586 Signed = true; 4587 MinBits = LN0->getMemoryVT().getSizeInBits(); 4588 PreExt = N0; 4589 } 4590 } 4591 4592 // Figure out how many bits we need to preserve this constant. 4593 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits(); 4594 4595 // Make sure we're not losing bits from the constant. 4596 if (MinBits > 0 && 4597 MinBits < C1.getBitWidth() && 4598 MinBits >= ReqdBits) { 4599 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4600 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4601 // Will get folded away. 4602 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4603 if (MinBits == 1 && C1 == 1) 4604 // Invert the condition. 4605 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4606 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4607 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4608 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4609 } 4610 4611 // If truncating the setcc operands is not desirable, we can still 4612 // simplify the expression in some cases: 4613 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4614 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4615 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4616 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4617 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4618 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4619 SDValue TopSetCC = N0->getOperand(0); 4620 unsigned N0Opc = N0->getOpcode(); 4621 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4622 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4623 TopSetCC.getOpcode() == ISD::SETCC && 4624 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4625 (isConstFalseVal(N1) || 4626 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4627 4628 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4629 (!N1C->isZero() && Cond == ISD::SETNE); 4630 4631 if (!Inverse) 4632 return TopSetCC; 4633 4634 ISD::CondCode InvCond = ISD::getSetCCInverse( 4635 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4636 TopSetCC.getOperand(0).getValueType()); 4637 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4638 TopSetCC.getOperand(1), 4639 InvCond); 4640 } 4641 } 4642 } 4643 4644 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4645 // equality or unsigned, and all 1 bits of the const are in the same 4646 // partial word, see if we can shorten the load. 4647 if (DCI.isBeforeLegalize() && 4648 !ISD::isSignedIntSetCC(Cond) && 4649 N0.getOpcode() == ISD::AND && C1 == 0 && 4650 N0.getNode()->hasOneUse() && 4651 isa<LoadSDNode>(N0.getOperand(0)) && 4652 N0.getOperand(0).getNode()->hasOneUse() && 4653 isa<ConstantSDNode>(N0.getOperand(1))) { 4654 auto *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4655 APInt bestMask; 4656 unsigned bestWidth = 0, bestOffset = 0; 4657 if (Lod->isSimple() && Lod->isUnindexed() && 4658 (Lod->getMemoryVT().isByteSized() || 4659 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) { 4660 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits(); 4661 unsigned origWidth = N0.getValueSizeInBits(); 4662 unsigned maskWidth = origWidth; 4663 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4664 // 8 bits, but have to be careful... 4665 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4666 origWidth = Lod->getMemoryVT().getSizeInBits(); 4667 const APInt &Mask = N0.getConstantOperandAPInt(1); 4668 // Only consider power-of-2 widths (and at least one byte) as candiates 4669 // for the narrowed load. 4670 for (unsigned width = 8; width < origWidth; width *= 2) { 4671 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width); 4672 if (!shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) 4673 continue; 4674 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4675 // Avoid accessing any padding here for now (we could use memWidth 4676 // instead of origWidth here otherwise). 4677 unsigned maxOffset = origWidth - width; 4678 for (unsigned offset = 0; offset <= maxOffset; offset += 8) { 4679 if (Mask.isSubsetOf(newMask)) { 4680 unsigned ptrOffset = 4681 Layout.isLittleEndian() ? offset : memWidth - width - offset; 4682 unsigned IsFast = 0; 4683 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8); 4684 if (allowsMemoryAccess( 4685 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(), 4686 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) && 4687 IsFast) { 4688 bestOffset = ptrOffset / 8; 4689 bestMask = Mask.lshr(offset); 4690 bestWidth = width; 4691 break; 4692 } 4693 } 4694 newMask <<= 8; 4695 } 4696 if (bestWidth) 4697 break; 4698 } 4699 } 4700 if (bestWidth) { 4701 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4702 SDValue Ptr = Lod->getBasePtr(); 4703 if (bestOffset != 0) 4704 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset)); 4705 SDValue NewLoad = 4706 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4707 Lod->getPointerInfo().getWithOffset(bestOffset), 4708 Lod->getOriginalAlign()); 4709 SDValue And = 4710 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4711 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT)); 4712 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond); 4713 } 4714 } 4715 4716 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4717 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4718 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4719 4720 // If the comparison constant has bits in the upper part, the 4721 // zero-extended value could never match. 4722 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4723 C1.getBitWidth() - InSize))) { 4724 switch (Cond) { 4725 case ISD::SETUGT: 4726 case ISD::SETUGE: 4727 case ISD::SETEQ: 4728 return DAG.getConstant(0, dl, VT); 4729 case ISD::SETULT: 4730 case ISD::SETULE: 4731 case ISD::SETNE: 4732 return DAG.getConstant(1, dl, VT); 4733 case ISD::SETGT: 4734 case ISD::SETGE: 4735 // True if the sign bit of C1 is set. 4736 return DAG.getConstant(C1.isNegative(), dl, VT); 4737 case ISD::SETLT: 4738 case ISD::SETLE: 4739 // True if the sign bit of C1 isn't set. 4740 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4741 default: 4742 break; 4743 } 4744 } 4745 4746 // Otherwise, we can perform the comparison with the low bits. 4747 switch (Cond) { 4748 case ISD::SETEQ: 4749 case ISD::SETNE: 4750 case ISD::SETUGT: 4751 case ISD::SETUGE: 4752 case ISD::SETULT: 4753 case ISD::SETULE: { 4754 EVT newVT = N0.getOperand(0).getValueType(); 4755 // FIXME: Should use isNarrowingProfitable. 4756 if (DCI.isBeforeLegalizeOps() || 4757 (isOperationLegal(ISD::SETCC, newVT) && 4758 isCondCodeLegal(Cond, newVT.getSimpleVT()) && 4759 isTypeDesirableForOp(ISD::SETCC, newVT))) { 4760 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4761 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4762 4763 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4764 NewConst, Cond); 4765 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4766 } 4767 break; 4768 } 4769 default: 4770 break; // todo, be more careful with signed comparisons 4771 } 4772 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4773 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4774 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4775 OpVT)) { 4776 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4777 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4778 EVT ExtDstTy = N0.getValueType(); 4779 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4780 4781 // If the constant doesn't fit into the number of bits for the source of 4782 // the sign extension, it is impossible for both sides to be equal. 4783 if (C1.getSignificantBits() > ExtSrcTyBits) 4784 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4785 4786 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4787 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4788 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4789 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4790 DAG.getConstant(Imm, dl, ExtDstTy)); 4791 if (!DCI.isCalledByLegalizer()) 4792 DCI.AddToWorklist(ZextOp.getNode()); 4793 // Otherwise, make this a use of a zext. 4794 return DAG.getSetCC(dl, VT, ZextOp, 4795 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4796 } else if ((N1C->isZero() || N1C->isOne()) && 4797 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4798 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are 4799 // excluded as they are handled below whilst checking for foldBooleans. 4800 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) && 4801 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4802 (N0.getValueType() == MVT::i1 || 4803 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4804 DAG.MaskedValueIsZero( 4805 N0, APInt::getBitsSetFrom(N0.getValueSizeInBits(), 1))) { 4806 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4807 if (TrueWhenTrue) 4808 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4809 // Invert the condition. 4810 if (N0.getOpcode() == ISD::SETCC) { 4811 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4812 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4813 if (DCI.isBeforeLegalizeOps() || 4814 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4815 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4816 } 4817 } 4818 4819 if ((N0.getOpcode() == ISD::XOR || 4820 (N0.getOpcode() == ISD::AND && 4821 N0.getOperand(0).getOpcode() == ISD::XOR && 4822 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4823 isOneConstant(N0.getOperand(1))) { 4824 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4825 // can only do this if the top bits are known zero. 4826 unsigned BitWidth = N0.getValueSizeInBits(); 4827 if (DAG.MaskedValueIsZero(N0, 4828 APInt::getHighBitsSet(BitWidth, 4829 BitWidth-1))) { 4830 // Okay, get the un-inverted input value. 4831 SDValue Val; 4832 if (N0.getOpcode() == ISD::XOR) { 4833 Val = N0.getOperand(0); 4834 } else { 4835 assert(N0.getOpcode() == ISD::AND && 4836 N0.getOperand(0).getOpcode() == ISD::XOR); 4837 // ((X^1)&1)^1 -> X & 1 4838 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4839 N0.getOperand(0).getOperand(0), 4840 N0.getOperand(1)); 4841 } 4842 4843 return DAG.getSetCC(dl, VT, Val, N1, 4844 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4845 } 4846 } else if (N1C->isOne()) { 4847 SDValue Op0 = N0; 4848 if (Op0.getOpcode() == ISD::TRUNCATE) 4849 Op0 = Op0.getOperand(0); 4850 4851 if ((Op0.getOpcode() == ISD::XOR) && 4852 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4853 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4854 SDValue XorLHS = Op0.getOperand(0); 4855 SDValue XorRHS = Op0.getOperand(1); 4856 // Ensure that the input setccs return an i1 type or 0/1 value. 4857 if (Op0.getValueType() == MVT::i1 || 4858 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4859 ZeroOrOneBooleanContent && 4860 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4861 ZeroOrOneBooleanContent)) { 4862 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4863 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4864 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4865 } 4866 } 4867 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4868 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4869 if (Op0.getValueType().bitsGT(VT)) 4870 Op0 = DAG.getNode(ISD::AND, dl, VT, 4871 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4872 DAG.getConstant(1, dl, VT)); 4873 else if (Op0.getValueType().bitsLT(VT)) 4874 Op0 = DAG.getNode(ISD::AND, dl, VT, 4875 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4876 DAG.getConstant(1, dl, VT)); 4877 4878 return DAG.getSetCC(dl, VT, Op0, 4879 DAG.getConstant(0, dl, Op0.getValueType()), 4880 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4881 } 4882 if (Op0.getOpcode() == ISD::AssertZext && 4883 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4884 return DAG.getSetCC(dl, VT, Op0, 4885 DAG.getConstant(0, dl, Op0.getValueType()), 4886 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4887 } 4888 } 4889 4890 // Given: 4891 // icmp eq/ne (urem %x, %y), 0 4892 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4893 // icmp eq/ne %x, 0 4894 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4895 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4896 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4897 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4898 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4899 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4900 } 4901 4902 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4903 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4904 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4905 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4906 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4907 N1C->isAllOnes()) { 4908 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4909 DAG.getConstant(0, dl, OpVT), 4910 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4911 } 4912 4913 if (SDValue V = 4914 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4915 return V; 4916 } 4917 4918 // These simplifications apply to splat vectors as well. 4919 // TODO: Handle more splat vector cases. 4920 if (auto *N1C = isConstOrConstSplat(N1)) { 4921 const APInt &C1 = N1C->getAPIntValue(); 4922 4923 APInt MinVal, MaxVal; 4924 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4925 if (ISD::isSignedIntSetCC(Cond)) { 4926 MinVal = APInt::getSignedMinValue(OperandBitSize); 4927 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4928 } else { 4929 MinVal = APInt::getMinValue(OperandBitSize); 4930 MaxVal = APInt::getMaxValue(OperandBitSize); 4931 } 4932 4933 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4934 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4935 // X >= MIN --> true 4936 if (C1 == MinVal) 4937 return DAG.getBoolConstant(true, dl, VT, OpVT); 4938 4939 if (!VT.isVector()) { // TODO: Support this for vectors. 4940 // X >= C0 --> X > (C0 - 1) 4941 APInt C = C1 - 1; 4942 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4943 if ((DCI.isBeforeLegalizeOps() || 4944 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4945 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4946 isLegalICmpImmediate(C.getSExtValue())))) { 4947 return DAG.getSetCC(dl, VT, N0, 4948 DAG.getConstant(C, dl, N1.getValueType()), 4949 NewCC); 4950 } 4951 } 4952 } 4953 4954 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4955 // X <= MAX --> true 4956 if (C1 == MaxVal) 4957 return DAG.getBoolConstant(true, dl, VT, OpVT); 4958 4959 // X <= C0 --> X < (C0 + 1) 4960 if (!VT.isVector()) { // TODO: Support this for vectors. 4961 APInt C = C1 + 1; 4962 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4963 if ((DCI.isBeforeLegalizeOps() || 4964 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4965 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4966 isLegalICmpImmediate(C.getSExtValue())))) { 4967 return DAG.getSetCC(dl, VT, N0, 4968 DAG.getConstant(C, dl, N1.getValueType()), 4969 NewCC); 4970 } 4971 } 4972 } 4973 4974 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4975 if (C1 == MinVal) 4976 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4977 4978 // TODO: Support this for vectors after legalize ops. 4979 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4980 // Canonicalize setlt X, Max --> setne X, Max 4981 if (C1 == MaxVal) 4982 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4983 4984 // If we have setult X, 1, turn it into seteq X, 0 4985 if (C1 == MinVal+1) 4986 return DAG.getSetCC(dl, VT, N0, 4987 DAG.getConstant(MinVal, dl, N0.getValueType()), 4988 ISD::SETEQ); 4989 } 4990 } 4991 4992 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4993 if (C1 == MaxVal) 4994 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4995 4996 // TODO: Support this for vectors after legalize ops. 4997 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4998 // Canonicalize setgt X, Min --> setne X, Min 4999 if (C1 == MinVal) 5000 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 5001 5002 // If we have setugt X, Max-1, turn it into seteq X, Max 5003 if (C1 == MaxVal-1) 5004 return DAG.getSetCC(dl, VT, N0, 5005 DAG.getConstant(MaxVal, dl, N0.getValueType()), 5006 ISD::SETEQ); 5007 } 5008 } 5009 5010 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 5011 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 5012 if (C1.isZero()) 5013 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 5014 VT, N0, N1, Cond, DCI, dl)) 5015 return CC; 5016 5017 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 5018 // For example, when high 32-bits of i64 X are known clear: 5019 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 5020 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 5021 bool CmpZero = N1C->isZero(); 5022 bool CmpNegOne = N1C->isAllOnes(); 5023 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 5024 // Match or(lo,shl(hi,bw/2)) pattern. 5025 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 5026 unsigned EltBits = V.getScalarValueSizeInBits(); 5027 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 5028 return false; 5029 SDValue LHS = V.getOperand(0); 5030 SDValue RHS = V.getOperand(1); 5031 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 5032 // Unshifted element must have zero upperbits. 5033 if (RHS.getOpcode() == ISD::SHL && 5034 isa<ConstantSDNode>(RHS.getOperand(1)) && 5035 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 5036 DAG.MaskedValueIsZero(LHS, HiBits)) { 5037 Lo = LHS; 5038 Hi = RHS.getOperand(0); 5039 return true; 5040 } 5041 if (LHS.getOpcode() == ISD::SHL && 5042 isa<ConstantSDNode>(LHS.getOperand(1)) && 5043 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 5044 DAG.MaskedValueIsZero(RHS, HiBits)) { 5045 Lo = RHS; 5046 Hi = LHS.getOperand(0); 5047 return true; 5048 } 5049 return false; 5050 }; 5051 5052 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 5053 unsigned EltBits = N0.getScalarValueSizeInBits(); 5054 unsigned HalfBits = EltBits / 2; 5055 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 5056 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 5057 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 5058 SDValue NewN0 = 5059 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 5060 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 5061 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 5062 }; 5063 5064 SDValue Lo, Hi; 5065 if (IsConcat(N0, Lo, Hi)) 5066 return MergeConcat(Lo, Hi); 5067 5068 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 5069 SDValue Lo0, Lo1, Hi0, Hi1; 5070 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 5071 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 5072 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 5073 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 5074 } 5075 } 5076 } 5077 } 5078 5079 // If we have "setcc X, C0", check to see if we can shrink the immediate 5080 // by changing cc. 5081 // TODO: Support this for vectors after legalize ops. 5082 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 5083 // SETUGT X, SINTMAX -> SETLT X, 0 5084 // SETUGE X, SINTMIN -> SETLT X, 0 5085 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 5086 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 5087 return DAG.getSetCC(dl, VT, N0, 5088 DAG.getConstant(0, dl, N1.getValueType()), 5089 ISD::SETLT); 5090 5091 // SETULT X, SINTMIN -> SETGT X, -1 5092 // SETULE X, SINTMAX -> SETGT X, -1 5093 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 5094 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 5095 return DAG.getSetCC(dl, VT, N0, 5096 DAG.getAllOnesConstant(dl, N1.getValueType()), 5097 ISD::SETGT); 5098 } 5099 } 5100 5101 // Back to non-vector simplifications. 5102 // TODO: Can we do these for vector splats? 5103 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 5104 const APInt &C1 = N1C->getAPIntValue(); 5105 EVT ShValTy = N0.getValueType(); 5106 5107 // Fold bit comparisons when we can. This will result in an 5108 // incorrect value when boolean false is negative one, unless 5109 // the bitsize is 1 in which case the false value is the same 5110 // in practice regardless of the representation. 5111 if ((VT.getSizeInBits() == 1 || 5112 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 5113 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5114 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 5115 N0.getOpcode() == ISD::AND) { 5116 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5117 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 5118 // Perform the xform if the AND RHS is a single bit. 5119 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 5120 if (AndRHS->getAPIntValue().isPowerOf2() && 5121 !shouldAvoidTransformToShift(ShValTy, ShCt)) { 5122 return DAG.getNode( 5123 ISD::TRUNCATE, dl, VT, 5124 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5125 DAG.getShiftAmountConstant(ShCt, ShValTy, dl))); 5126 } 5127 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 5128 // (X & 8) == 8 --> (X & 8) >> 3 5129 // Perform the xform if C1 is a single bit. 5130 unsigned ShCt = C1.logBase2(); 5131 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) { 5132 return DAG.getNode( 5133 ISD::TRUNCATE, dl, VT, 5134 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5135 DAG.getShiftAmountConstant(ShCt, ShValTy, dl))); 5136 } 5137 } 5138 } 5139 } 5140 5141 if (C1.getSignificantBits() <= 64 && 5142 !isLegalICmpImmediate(C1.getSExtValue())) { 5143 // (X & -256) == 256 -> (X >> 8) == 1 5144 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5145 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 5146 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5147 const APInt &AndRHSC = AndRHS->getAPIntValue(); 5148 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) { 5149 unsigned ShiftBits = AndRHSC.countr_zero(); 5150 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5151 SDValue Shift = DAG.getNode( 5152 ISD::SRL, dl, ShValTy, N0.getOperand(0), 5153 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl)); 5154 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 5155 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 5156 } 5157 } 5158 } 5159 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 5160 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 5161 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 5162 // X < 0x100000000 -> (X >> 32) < 1 5163 // X >= 0x100000000 -> (X >> 32) >= 1 5164 // X <= 0x0ffffffff -> (X >> 32) < 1 5165 // X > 0x0ffffffff -> (X >> 32) >= 1 5166 unsigned ShiftBits; 5167 APInt NewC = C1; 5168 ISD::CondCode NewCond = Cond; 5169 if (AdjOne) { 5170 ShiftBits = C1.countr_one(); 5171 NewC = NewC + 1; 5172 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 5173 } else { 5174 ShiftBits = C1.countr_zero(); 5175 } 5176 NewC.lshrInPlace(ShiftBits); 5177 if (ShiftBits && NewC.getSignificantBits() <= 64 && 5178 isLegalICmpImmediate(NewC.getSExtValue()) && 5179 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5180 SDValue Shift = 5181 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5182 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl)); 5183 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 5184 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 5185 } 5186 } 5187 } 5188 } 5189 5190 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 5191 auto *CFP = cast<ConstantFPSDNode>(N1); 5192 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 5193 5194 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 5195 // constant if knowing that the operand is non-nan is enough. We prefer to 5196 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 5197 // materialize 0.0. 5198 if (Cond == ISD::SETO || Cond == ISD::SETUO) 5199 return DAG.getSetCC(dl, VT, N0, N0, Cond); 5200 5201 // setcc (fneg x), C -> setcc swap(pred) x, -C 5202 if (N0.getOpcode() == ISD::FNEG) { 5203 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 5204 if (DCI.isBeforeLegalizeOps() || 5205 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 5206 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 5207 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 5208 } 5209 } 5210 5211 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf 5212 if (isOperationLegalOrCustom(ISD::IS_FPCLASS, N0.getValueType()) && 5213 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) { 5214 bool IsFabs = N0.getOpcode() == ISD::FABS; 5215 SDValue Op = IsFabs ? N0.getOperand(0) : N0; 5216 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) { 5217 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf) 5218 : (IsFabs ? fcInf : fcPosInf); 5219 if (Cond == ISD::SETUEQ) 5220 Flag |= fcNan; 5221 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op, 5222 DAG.getTargetConstant(Flag, dl, MVT::i32)); 5223 } 5224 } 5225 5226 // If the condition is not legal, see if we can find an equivalent one 5227 // which is legal. 5228 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 5229 // If the comparison was an awkward floating-point == or != and one of 5230 // the comparison operands is infinity or negative infinity, convert the 5231 // condition to a less-awkward <= or >=. 5232 if (CFP->getValueAPF().isInfinity()) { 5233 bool IsNegInf = CFP->getValueAPF().isNegative(); 5234 ISD::CondCode NewCond = ISD::SETCC_INVALID; 5235 switch (Cond) { 5236 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 5237 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 5238 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 5239 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 5240 default: break; 5241 } 5242 if (NewCond != ISD::SETCC_INVALID && 5243 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 5244 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5245 } 5246 } 5247 } 5248 5249 if (N0 == N1) { 5250 // The sext(setcc()) => setcc() optimization relies on the appropriate 5251 // constant being emitted. 5252 assert(!N0.getValueType().isInteger() && 5253 "Integer types should be handled by FoldSetCC"); 5254 5255 bool EqTrue = ISD::isTrueWhenEqual(Cond); 5256 unsigned UOF = ISD::getUnorderedFlavor(Cond); 5257 if (UOF == 2) // FP operators that are undefined on NaNs. 5258 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5259 if (UOF == unsigned(EqTrue)) 5260 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5261 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 5262 // if it is not already. 5263 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 5264 if (NewCond != Cond && 5265 (DCI.isBeforeLegalizeOps() || 5266 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 5267 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5268 } 5269 5270 // ~X > ~Y --> Y > X 5271 // ~X < ~Y --> Y < X 5272 // ~X < C --> X > ~C 5273 // ~X > C --> X < ~C 5274 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) && 5275 N0.getValueType().isInteger()) { 5276 if (isBitwiseNot(N0)) { 5277 if (isBitwiseNot(N1)) 5278 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond); 5279 5280 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 5281 !DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(0))) { 5282 SDValue Not = DAG.getNOT(dl, N1, OpVT); 5283 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond); 5284 } 5285 } 5286 } 5287 5288 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5289 N0.getValueType().isInteger()) { 5290 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 5291 N0.getOpcode() == ISD::XOR) { 5292 // Simplify (X+Y) == (X+Z) --> Y == Z 5293 if (N0.getOpcode() == N1.getOpcode()) { 5294 if (N0.getOperand(0) == N1.getOperand(0)) 5295 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 5296 if (N0.getOperand(1) == N1.getOperand(1)) 5297 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 5298 if (isCommutativeBinOp(N0.getOpcode())) { 5299 // If X op Y == Y op X, try other combinations. 5300 if (N0.getOperand(0) == N1.getOperand(1)) 5301 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 5302 Cond); 5303 if (N0.getOperand(1) == N1.getOperand(0)) 5304 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 5305 Cond); 5306 } 5307 } 5308 5309 // If RHS is a legal immediate value for a compare instruction, we need 5310 // to be careful about increasing register pressure needlessly. 5311 bool LegalRHSImm = false; 5312 5313 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 5314 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5315 // Turn (X+C1) == C2 --> X == C2-C1 5316 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 5317 return DAG.getSetCC( 5318 dl, VT, N0.getOperand(0), 5319 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 5320 dl, N0.getValueType()), 5321 Cond); 5322 5323 // Turn (X^C1) == C2 --> X == C1^C2 5324 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 5325 return DAG.getSetCC( 5326 dl, VT, N0.getOperand(0), 5327 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 5328 dl, N0.getValueType()), 5329 Cond); 5330 } 5331 5332 // Turn (C1-X) == C2 --> X == C1-C2 5333 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 5334 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 5335 return DAG.getSetCC( 5336 dl, VT, N0.getOperand(1), 5337 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 5338 dl, N0.getValueType()), 5339 Cond); 5340 5341 // Could RHSC fold directly into a compare? 5342 if (RHSC->getValueType(0).getSizeInBits() <= 64) 5343 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 5344 } 5345 5346 // (X+Y) == X --> Y == 0 and similar folds. 5347 // Don't do this if X is an immediate that can fold into a cmp 5348 // instruction and X+Y has other uses. It could be an induction variable 5349 // chain, and the transform would increase register pressure. 5350 if (!LegalRHSImm || N0.hasOneUse()) 5351 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 5352 return V; 5353 } 5354 5355 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 5356 N1.getOpcode() == ISD::XOR) 5357 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 5358 return V; 5359 5360 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 5361 return V; 5362 } 5363 5364 // Fold remainder of division by a constant. 5365 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 5366 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 5367 // When division is cheap or optimizing for minimum size, 5368 // fall through to DIVREM creation by skipping this fold. 5369 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 5370 if (N0.getOpcode() == ISD::UREM) { 5371 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5372 return Folded; 5373 } else if (N0.getOpcode() == ISD::SREM) { 5374 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5375 return Folded; 5376 } 5377 } 5378 } 5379 5380 // Fold away ALL boolean setcc's. 5381 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 5382 SDValue Temp; 5383 switch (Cond) { 5384 default: llvm_unreachable("Unknown integer setcc!"); 5385 case ISD::SETEQ: // X == Y -> ~(X^Y) 5386 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5387 N0 = DAG.getNOT(dl, Temp, OpVT); 5388 if (!DCI.isCalledByLegalizer()) 5389 DCI.AddToWorklist(Temp.getNode()); 5390 break; 5391 case ISD::SETNE: // X != Y --> (X^Y) 5392 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5393 break; 5394 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 5395 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 5396 Temp = DAG.getNOT(dl, N0, OpVT); 5397 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 5398 if (!DCI.isCalledByLegalizer()) 5399 DCI.AddToWorklist(Temp.getNode()); 5400 break; 5401 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 5402 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 5403 Temp = DAG.getNOT(dl, N1, OpVT); 5404 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 5405 if (!DCI.isCalledByLegalizer()) 5406 DCI.AddToWorklist(Temp.getNode()); 5407 break; 5408 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 5409 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 5410 Temp = DAG.getNOT(dl, N0, OpVT); 5411 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 5412 if (!DCI.isCalledByLegalizer()) 5413 DCI.AddToWorklist(Temp.getNode()); 5414 break; 5415 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 5416 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 5417 Temp = DAG.getNOT(dl, N1, OpVT); 5418 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 5419 break; 5420 } 5421 if (VT.getScalarType() != MVT::i1) { 5422 if (!DCI.isCalledByLegalizer()) 5423 DCI.AddToWorklist(N0.getNode()); 5424 // FIXME: If running after legalize, we probably can't do this. 5425 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 5426 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 5427 } 5428 return N0; 5429 } 5430 5431 // Could not fold it. 5432 return SDValue(); 5433 } 5434 5435 /// Returns true (and the GlobalValue and the offset) if the node is a 5436 /// GlobalAddress + offset. 5437 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 5438 int64_t &Offset) const { 5439 5440 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 5441 5442 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 5443 GA = GASD->getGlobal(); 5444 Offset += GASD->getOffset(); 5445 return true; 5446 } 5447 5448 if (N->getOpcode() == ISD::ADD) { 5449 SDValue N1 = N->getOperand(0); 5450 SDValue N2 = N->getOperand(1); 5451 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 5452 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 5453 Offset += V->getSExtValue(); 5454 return true; 5455 } 5456 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 5457 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 5458 Offset += V->getSExtValue(); 5459 return true; 5460 } 5461 } 5462 } 5463 5464 return false; 5465 } 5466 5467 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5468 DAGCombinerInfo &DCI) const { 5469 // Default implementation: no optimization. 5470 return SDValue(); 5471 } 5472 5473 //===----------------------------------------------------------------------===// 5474 // Inline Assembler Implementation Methods 5475 //===----------------------------------------------------------------------===// 5476 5477 TargetLowering::ConstraintType 5478 TargetLowering::getConstraintType(StringRef Constraint) const { 5479 unsigned S = Constraint.size(); 5480 5481 if (S == 1) { 5482 switch (Constraint[0]) { 5483 default: break; 5484 case 'r': 5485 return C_RegisterClass; 5486 case 'm': // memory 5487 case 'o': // offsetable 5488 case 'V': // not offsetable 5489 return C_Memory; 5490 case 'p': // Address. 5491 return C_Address; 5492 case 'n': // Simple Integer 5493 case 'E': // Floating Point Constant 5494 case 'F': // Floating Point Constant 5495 return C_Immediate; 5496 case 'i': // Simple Integer or Relocatable Constant 5497 case 's': // Relocatable Constant 5498 case 'X': // Allow ANY value. 5499 case 'I': // Target registers. 5500 case 'J': 5501 case 'K': 5502 case 'L': 5503 case 'M': 5504 case 'N': 5505 case 'O': 5506 case 'P': 5507 case '<': 5508 case '>': 5509 return C_Other; 5510 } 5511 } 5512 5513 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5514 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5515 return C_Memory; 5516 return C_Register; 5517 } 5518 return C_Unknown; 5519 } 5520 5521 /// Try to replace an X constraint, which matches anything, with another that 5522 /// has more specific requirements based on the type of the corresponding 5523 /// operand. 5524 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5525 if (ConstraintVT.isInteger()) 5526 return "r"; 5527 if (ConstraintVT.isFloatingPoint()) 5528 return "f"; // works for many targets 5529 return nullptr; 5530 } 5531 5532 SDValue TargetLowering::LowerAsmOutputForConstraint( 5533 SDValue &Chain, SDValue &Glue, const SDLoc &DL, 5534 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5535 return SDValue(); 5536 } 5537 5538 /// Lower the specified operand into the Ops vector. 5539 /// If it is invalid, don't add anything to Ops. 5540 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5541 StringRef Constraint, 5542 std::vector<SDValue> &Ops, 5543 SelectionDAG &DAG) const { 5544 5545 if (Constraint.size() > 1) 5546 return; 5547 5548 char ConstraintLetter = Constraint[0]; 5549 switch (ConstraintLetter) { 5550 default: break; 5551 case 'X': // Allows any operand 5552 case 'i': // Simple Integer or Relocatable Constant 5553 case 'n': // Simple Integer 5554 case 's': { // Relocatable Constant 5555 5556 ConstantSDNode *C; 5557 uint64_t Offset = 0; 5558 5559 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5560 // etc., since getelementpointer is variadic. We can't use 5561 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5562 // while in this case the GA may be furthest from the root node which is 5563 // likely an ISD::ADD. 5564 while (true) { 5565 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5566 // gcc prints these as sign extended. Sign extend value to 64 bits 5567 // now; without this it would get ZExt'd later in 5568 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5569 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5570 BooleanContent BCont = getBooleanContents(MVT::i64); 5571 ISD::NodeType ExtOpc = 5572 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5573 int64_t ExtVal = 5574 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5575 Ops.push_back( 5576 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5577 return; 5578 } 5579 if (ConstraintLetter != 'n') { 5580 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5581 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5582 GA->getValueType(0), 5583 Offset + GA->getOffset())); 5584 return; 5585 } 5586 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5587 Ops.push_back(DAG.getTargetBlockAddress( 5588 BA->getBlockAddress(), BA->getValueType(0), 5589 Offset + BA->getOffset(), BA->getTargetFlags())); 5590 return; 5591 } 5592 if (isa<BasicBlockSDNode>(Op)) { 5593 Ops.push_back(Op); 5594 return; 5595 } 5596 } 5597 const unsigned OpCode = Op.getOpcode(); 5598 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5599 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5600 Op = Op.getOperand(1); 5601 // Subtraction is not commutative. 5602 else if (OpCode == ISD::ADD && 5603 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5604 Op = Op.getOperand(0); 5605 else 5606 return; 5607 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5608 continue; 5609 } 5610 return; 5611 } 5612 break; 5613 } 5614 } 5615 } 5616 5617 void TargetLowering::CollectTargetIntrinsicOperands( 5618 const CallInst &I, SmallVectorImpl<SDValue> &Ops, SelectionDAG &DAG) const { 5619 } 5620 5621 std::pair<unsigned, const TargetRegisterClass *> 5622 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5623 StringRef Constraint, 5624 MVT VT) const { 5625 if (!Constraint.starts_with("{")) 5626 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5627 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5628 5629 // Remove the braces from around the name. 5630 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5631 5632 std::pair<unsigned, const TargetRegisterClass *> R = 5633 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5634 5635 // Figure out which register class contains this reg. 5636 for (const TargetRegisterClass *RC : RI->regclasses()) { 5637 // If none of the value types for this register class are valid, we 5638 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5639 if (!isLegalRC(*RI, *RC)) 5640 continue; 5641 5642 for (const MCPhysReg &PR : *RC) { 5643 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5644 std::pair<unsigned, const TargetRegisterClass *> S = 5645 std::make_pair(PR, RC); 5646 5647 // If this register class has the requested value type, return it, 5648 // otherwise keep searching and return the first class found 5649 // if no other is found which explicitly has the requested type. 5650 if (RI->isTypeLegalForClass(*RC, VT)) 5651 return S; 5652 if (!R.second) 5653 R = S; 5654 } 5655 } 5656 } 5657 5658 return R; 5659 } 5660 5661 //===----------------------------------------------------------------------===// 5662 // Constraint Selection. 5663 5664 /// Return true of this is an input operand that is a matching constraint like 5665 /// "4". 5666 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5667 assert(!ConstraintCode.empty() && "No known constraint!"); 5668 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5669 } 5670 5671 /// If this is an input matching constraint, this method returns the output 5672 /// operand it matches. 5673 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5674 assert(!ConstraintCode.empty() && "No known constraint!"); 5675 return atoi(ConstraintCode.c_str()); 5676 } 5677 5678 /// Split up the constraint string from the inline assembly value into the 5679 /// specific constraints and their prefixes, and also tie in the associated 5680 /// operand values. 5681 /// If this returns an empty vector, and if the constraint string itself 5682 /// isn't empty, there was an error parsing. 5683 TargetLowering::AsmOperandInfoVector 5684 TargetLowering::ParseConstraints(const DataLayout &DL, 5685 const TargetRegisterInfo *TRI, 5686 const CallBase &Call) const { 5687 /// Information about all of the constraints. 5688 AsmOperandInfoVector ConstraintOperands; 5689 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5690 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5691 5692 // Do a prepass over the constraints, canonicalizing them, and building up the 5693 // ConstraintOperands list. 5694 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5695 unsigned ResNo = 0; // ResNo - The result number of the next output. 5696 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number. 5697 5698 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5699 ConstraintOperands.emplace_back(std::move(CI)); 5700 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5701 5702 // Update multiple alternative constraint count. 5703 if (OpInfo.multipleAlternatives.size() > maCount) 5704 maCount = OpInfo.multipleAlternatives.size(); 5705 5706 OpInfo.ConstraintVT = MVT::Other; 5707 5708 // Compute the value type for each operand. 5709 switch (OpInfo.Type) { 5710 case InlineAsm::isOutput: 5711 // Indirect outputs just consume an argument. 5712 if (OpInfo.isIndirect) { 5713 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5714 break; 5715 } 5716 5717 // The return value of the call is this value. As such, there is no 5718 // corresponding argument. 5719 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5720 if (auto *STy = dyn_cast<StructType>(Call.getType())) { 5721 OpInfo.ConstraintVT = 5722 getSimpleValueType(DL, STy->getElementType(ResNo)); 5723 } else { 5724 assert(ResNo == 0 && "Asm only has one result!"); 5725 OpInfo.ConstraintVT = 5726 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5727 } 5728 ++ResNo; 5729 break; 5730 case InlineAsm::isInput: 5731 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5732 break; 5733 case InlineAsm::isLabel: 5734 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo); 5735 ++LabelNo; 5736 continue; 5737 case InlineAsm::isClobber: 5738 // Nothing to do. 5739 break; 5740 } 5741 5742 if (OpInfo.CallOperandVal) { 5743 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5744 if (OpInfo.isIndirect) { 5745 OpTy = Call.getParamElementType(ArgNo); 5746 assert(OpTy && "Indirect operand must have elementtype attribute"); 5747 } 5748 5749 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5750 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5751 if (STy->getNumElements() == 1) 5752 OpTy = STy->getElementType(0); 5753 5754 // If OpTy is not a single value, it may be a struct/union that we 5755 // can tile with integers. 5756 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5757 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5758 switch (BitSize) { 5759 default: break; 5760 case 1: 5761 case 8: 5762 case 16: 5763 case 32: 5764 case 64: 5765 case 128: 5766 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5767 break; 5768 } 5769 } 5770 5771 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5772 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5773 ArgNo++; 5774 } 5775 } 5776 5777 // If we have multiple alternative constraints, select the best alternative. 5778 if (!ConstraintOperands.empty()) { 5779 if (maCount) { 5780 unsigned bestMAIndex = 0; 5781 int bestWeight = -1; 5782 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5783 int weight = -1; 5784 unsigned maIndex; 5785 // Compute the sums of the weights for each alternative, keeping track 5786 // of the best (highest weight) one so far. 5787 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5788 int weightSum = 0; 5789 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5790 cIndex != eIndex; ++cIndex) { 5791 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5792 if (OpInfo.Type == InlineAsm::isClobber) 5793 continue; 5794 5795 // If this is an output operand with a matching input operand, 5796 // look up the matching input. If their types mismatch, e.g. one 5797 // is an integer, the other is floating point, or their sizes are 5798 // different, flag it as an maCantMatch. 5799 if (OpInfo.hasMatchingInput()) { 5800 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5801 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5802 if ((OpInfo.ConstraintVT.isInteger() != 5803 Input.ConstraintVT.isInteger()) || 5804 (OpInfo.ConstraintVT.getSizeInBits() != 5805 Input.ConstraintVT.getSizeInBits())) { 5806 weightSum = -1; // Can't match. 5807 break; 5808 } 5809 } 5810 } 5811 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5812 if (weight == -1) { 5813 weightSum = -1; 5814 break; 5815 } 5816 weightSum += weight; 5817 } 5818 // Update best. 5819 if (weightSum > bestWeight) { 5820 bestWeight = weightSum; 5821 bestMAIndex = maIndex; 5822 } 5823 } 5824 5825 // Now select chosen alternative in each constraint. 5826 for (AsmOperandInfo &cInfo : ConstraintOperands) 5827 if (cInfo.Type != InlineAsm::isClobber) 5828 cInfo.selectAlternative(bestMAIndex); 5829 } 5830 } 5831 5832 // Check and hook up tied operands, choose constraint code to use. 5833 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5834 cIndex != eIndex; ++cIndex) { 5835 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5836 5837 // If this is an output operand with a matching input operand, look up the 5838 // matching input. If their types mismatch, e.g. one is an integer, the 5839 // other is floating point, or their sizes are different, flag it as an 5840 // error. 5841 if (OpInfo.hasMatchingInput()) { 5842 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5843 5844 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5845 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5846 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5847 OpInfo.ConstraintVT); 5848 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5849 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5850 Input.ConstraintVT); 5851 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() || 5852 OpInfo.ConstraintVT.isFloatingPoint(); 5853 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() || 5854 Input.ConstraintVT.isFloatingPoint(); 5855 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || 5856 (MatchRC.second != InputRC.second)) { 5857 report_fatal_error("Unsupported asm: input constraint" 5858 " with a matching output constraint of" 5859 " incompatible type!"); 5860 } 5861 } 5862 } 5863 } 5864 5865 return ConstraintOperands; 5866 } 5867 5868 /// Return a number indicating our preference for chosing a type of constraint 5869 /// over another, for the purpose of sorting them. Immediates are almost always 5870 /// preferrable (when they can be emitted). A higher return value means a 5871 /// stronger preference for one constraint type relative to another. 5872 /// FIXME: We should prefer registers over memory but doing so may lead to 5873 /// unrecoverable register exhaustion later. 5874 /// https://github.com/llvm/llvm-project/issues/20571 5875 static unsigned getConstraintPiority(TargetLowering::ConstraintType CT) { 5876 switch (CT) { 5877 case TargetLowering::C_Immediate: 5878 case TargetLowering::C_Other: 5879 return 4; 5880 case TargetLowering::C_Memory: 5881 case TargetLowering::C_Address: 5882 return 3; 5883 case TargetLowering::C_RegisterClass: 5884 return 2; 5885 case TargetLowering::C_Register: 5886 return 1; 5887 case TargetLowering::C_Unknown: 5888 return 0; 5889 } 5890 llvm_unreachable("Invalid constraint type"); 5891 } 5892 5893 /// Examine constraint type and operand type and determine a weight value. 5894 /// This object must already have been set up with the operand type 5895 /// and the current alternative constraint selected. 5896 TargetLowering::ConstraintWeight 5897 TargetLowering::getMultipleConstraintMatchWeight( 5898 AsmOperandInfo &info, int maIndex) const { 5899 InlineAsm::ConstraintCodeVector *rCodes; 5900 if (maIndex >= (int)info.multipleAlternatives.size()) 5901 rCodes = &info.Codes; 5902 else 5903 rCodes = &info.multipleAlternatives[maIndex].Codes; 5904 ConstraintWeight BestWeight = CW_Invalid; 5905 5906 // Loop over the options, keeping track of the most general one. 5907 for (const std::string &rCode : *rCodes) { 5908 ConstraintWeight weight = 5909 getSingleConstraintMatchWeight(info, rCode.c_str()); 5910 if (weight > BestWeight) 5911 BestWeight = weight; 5912 } 5913 5914 return BestWeight; 5915 } 5916 5917 /// Examine constraint type and operand type and determine a weight value. 5918 /// This object must already have been set up with the operand type 5919 /// and the current alternative constraint selected. 5920 TargetLowering::ConstraintWeight 5921 TargetLowering::getSingleConstraintMatchWeight( 5922 AsmOperandInfo &info, const char *constraint) const { 5923 ConstraintWeight weight = CW_Invalid; 5924 Value *CallOperandVal = info.CallOperandVal; 5925 // If we don't have a value, we can't do a match, 5926 // but allow it at the lowest weight. 5927 if (!CallOperandVal) 5928 return CW_Default; 5929 // Look at the constraint type. 5930 switch (*constraint) { 5931 case 'i': // immediate integer. 5932 case 'n': // immediate integer with a known value. 5933 if (isa<ConstantInt>(CallOperandVal)) 5934 weight = CW_Constant; 5935 break; 5936 case 's': // non-explicit intregal immediate. 5937 if (isa<GlobalValue>(CallOperandVal)) 5938 weight = CW_Constant; 5939 break; 5940 case 'E': // immediate float if host format. 5941 case 'F': // immediate float. 5942 if (isa<ConstantFP>(CallOperandVal)) 5943 weight = CW_Constant; 5944 break; 5945 case '<': // memory operand with autodecrement. 5946 case '>': // memory operand with autoincrement. 5947 case 'm': // memory operand. 5948 case 'o': // offsettable memory operand 5949 case 'V': // non-offsettable memory operand 5950 weight = CW_Memory; 5951 break; 5952 case 'r': // general register. 5953 case 'g': // general register, memory operand or immediate integer. 5954 // note: Clang converts "g" to "imr". 5955 if (CallOperandVal->getType()->isIntegerTy()) 5956 weight = CW_Register; 5957 break; 5958 case 'X': // any operand. 5959 default: 5960 weight = CW_Default; 5961 break; 5962 } 5963 return weight; 5964 } 5965 5966 /// If there are multiple different constraints that we could pick for this 5967 /// operand (e.g. "imr") try to pick the 'best' one. 5968 /// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall 5969 /// into seven classes: 5970 /// Register -> one specific register 5971 /// RegisterClass -> a group of regs 5972 /// Memory -> memory 5973 /// Address -> a symbolic memory reference 5974 /// Immediate -> immediate values 5975 /// Other -> magic values (such as "Flag Output Operands") 5976 /// Unknown -> something we don't recognize yet and can't handle 5977 /// Ideally, we would pick the most specific constraint possible: if we have 5978 /// something that fits into a register, we would pick it. The problem here 5979 /// is that if we have something that could either be in a register or in 5980 /// memory that use of the register could cause selection of *other* 5981 /// operands to fail: they might only succeed if we pick memory. Because of 5982 /// this the heuristic we use is: 5983 /// 5984 /// 1) If there is an 'other' constraint, and if the operand is valid for 5985 /// that constraint, use it. This makes us take advantage of 'i' 5986 /// constraints when available. 5987 /// 2) Otherwise, pick the most general constraint present. This prefers 5988 /// 'm' over 'r', for example. 5989 /// 5990 TargetLowering::ConstraintGroup TargetLowering::getConstraintPreferences( 5991 TargetLowering::AsmOperandInfo &OpInfo) const { 5992 ConstraintGroup Ret; 5993 5994 Ret.reserve(OpInfo.Codes.size()); 5995 for (StringRef Code : OpInfo.Codes) { 5996 TargetLowering::ConstraintType CType = getConstraintType(Code); 5997 5998 // Indirect 'other' or 'immediate' constraints are not allowed. 5999 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 6000 CType == TargetLowering::C_Register || 6001 CType == TargetLowering::C_RegisterClass)) 6002 continue; 6003 6004 // Things with matching constraints can only be registers, per gcc 6005 // documentation. This mainly affects "g" constraints. 6006 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 6007 continue; 6008 6009 Ret.emplace_back(Code, CType); 6010 } 6011 6012 std::stable_sort( 6013 Ret.begin(), Ret.end(), [](ConstraintPair a, ConstraintPair b) { 6014 return getConstraintPiority(a.second) > getConstraintPiority(b.second); 6015 }); 6016 6017 return Ret; 6018 } 6019 6020 /// If we have an immediate, see if we can lower it. Return true if we can, 6021 /// false otherwise. 6022 static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, 6023 SDValue Op, SelectionDAG *DAG, 6024 const TargetLowering &TLI) { 6025 6026 assert((P.second == TargetLowering::C_Other || 6027 P.second == TargetLowering::C_Immediate) && 6028 "need immediate or other"); 6029 6030 if (!Op.getNode()) 6031 return false; 6032 6033 std::vector<SDValue> ResultOps; 6034 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG); 6035 return !ResultOps.empty(); 6036 } 6037 6038 /// Determines the constraint code and constraint type to use for the specific 6039 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 6040 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 6041 SDValue Op, 6042 SelectionDAG *DAG) const { 6043 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 6044 6045 // Single-letter constraints ('r') are very common. 6046 if (OpInfo.Codes.size() == 1) { 6047 OpInfo.ConstraintCode = OpInfo.Codes[0]; 6048 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 6049 } else { 6050 ConstraintGroup G = getConstraintPreferences(OpInfo); 6051 if (G.empty()) 6052 return; 6053 6054 unsigned BestIdx = 0; 6055 for (const unsigned E = G.size(); 6056 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other || 6057 G[BestIdx].second == TargetLowering::C_Immediate); 6058 ++BestIdx) { 6059 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this)) 6060 break; 6061 // If we're out of constraints, just pick the first one. 6062 if (BestIdx + 1 == E) { 6063 BestIdx = 0; 6064 break; 6065 } 6066 } 6067 6068 OpInfo.ConstraintCode = G[BestIdx].first; 6069 OpInfo.ConstraintType = G[BestIdx].second; 6070 } 6071 6072 // 'X' matches anything. 6073 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 6074 // Constants are handled elsewhere. For Functions, the type here is the 6075 // type of the result, which is not what we want to look at; leave them 6076 // alone. 6077 Value *v = OpInfo.CallOperandVal; 6078 if (isa<ConstantInt>(v) || isa<Function>(v)) { 6079 return; 6080 } 6081 6082 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 6083 OpInfo.ConstraintCode = "i"; 6084 return; 6085 } 6086 6087 // Otherwise, try to resolve it to something we know about by looking at 6088 // the actual operand type. 6089 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 6090 OpInfo.ConstraintCode = Repl; 6091 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 6092 } 6093 } 6094 } 6095 6096 /// Given an exact SDIV by a constant, create a multiplication 6097 /// with the multiplicative inverse of the constant. 6098 /// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242 6099 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 6100 const SDLoc &dl, SelectionDAG &DAG, 6101 SmallVectorImpl<SDNode *> &Created) { 6102 SDValue Op0 = N->getOperand(0); 6103 SDValue Op1 = N->getOperand(1); 6104 EVT VT = N->getValueType(0); 6105 EVT SVT = VT.getScalarType(); 6106 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 6107 EVT ShSVT = ShVT.getScalarType(); 6108 6109 bool UseSRA = false; 6110 SmallVector<SDValue, 16> Shifts, Factors; 6111 6112 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6113 if (C->isZero()) 6114 return false; 6115 APInt Divisor = C->getAPIntValue(); 6116 unsigned Shift = Divisor.countr_zero(); 6117 if (Shift) { 6118 Divisor.ashrInPlace(Shift); 6119 UseSRA = true; 6120 } 6121 APInt Factor = Divisor.multiplicativeInverse(); 6122 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 6123 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 6124 return true; 6125 }; 6126 6127 // Collect all magic values from the build vector. 6128 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 6129 return SDValue(); 6130 6131 SDValue Shift, Factor; 6132 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 6133 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6134 Factor = DAG.getBuildVector(VT, dl, Factors); 6135 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 6136 assert(Shifts.size() == 1 && Factors.size() == 1 && 6137 "Expected matchUnaryPredicate to return one element for scalable " 6138 "vectors"); 6139 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6140 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6141 } else { 6142 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 6143 Shift = Shifts[0]; 6144 Factor = Factors[0]; 6145 } 6146 6147 SDValue Res = Op0; 6148 if (UseSRA) { 6149 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact); 6150 Created.push_back(Res.getNode()); 6151 } 6152 6153 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 6154 } 6155 6156 /// Given an exact UDIV by a constant, create a multiplication 6157 /// with the multiplicative inverse of the constant. 6158 /// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242 6159 static SDValue BuildExactUDIV(const TargetLowering &TLI, SDNode *N, 6160 const SDLoc &dl, SelectionDAG &DAG, 6161 SmallVectorImpl<SDNode *> &Created) { 6162 EVT VT = N->getValueType(0); 6163 EVT SVT = VT.getScalarType(); 6164 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 6165 EVT ShSVT = ShVT.getScalarType(); 6166 6167 bool UseSRL = false; 6168 SmallVector<SDValue, 16> Shifts, Factors; 6169 6170 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 6171 if (C->isZero()) 6172 return false; 6173 APInt Divisor = C->getAPIntValue(); 6174 unsigned Shift = Divisor.countr_zero(); 6175 if (Shift) { 6176 Divisor.lshrInPlace(Shift); 6177 UseSRL = true; 6178 } 6179 // Calculate the multiplicative inverse modulo BW. 6180 APInt Factor = Divisor.multiplicativeInverse(); 6181 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 6182 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 6183 return true; 6184 }; 6185 6186 SDValue Op1 = N->getOperand(1); 6187 6188 // Collect all magic values from the build vector. 6189 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern)) 6190 return SDValue(); 6191 6192 SDValue Shift, Factor; 6193 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 6194 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6195 Factor = DAG.getBuildVector(VT, dl, Factors); 6196 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 6197 assert(Shifts.size() == 1 && Factors.size() == 1 && 6198 "Expected matchUnaryPredicate to return one element for scalable " 6199 "vectors"); 6200 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6201 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6202 } else { 6203 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 6204 Shift = Shifts[0]; 6205 Factor = Factors[0]; 6206 } 6207 6208 SDValue Res = N->getOperand(0); 6209 if (UseSRL) { 6210 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact); 6211 Created.push_back(Res.getNode()); 6212 } 6213 6214 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 6215 } 6216 6217 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 6218 SelectionDAG &DAG, 6219 SmallVectorImpl<SDNode *> &Created) const { 6220 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6221 if (isIntDivCheap(N->getValueType(0), Attr)) 6222 return SDValue(N, 0); // Lower SDIV as SDIV 6223 return SDValue(); 6224 } 6225 6226 SDValue 6227 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 6228 SelectionDAG &DAG, 6229 SmallVectorImpl<SDNode *> &Created) const { 6230 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6231 if (isIntDivCheap(N->getValueType(0), Attr)) 6232 return SDValue(N, 0); // Lower SREM as SREM 6233 return SDValue(); 6234 } 6235 6236 /// Build sdiv by power-of-2 with conditional move instructions 6237 /// Ref: "Hacker's Delight" by Henry Warren 10-1 6238 /// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into: 6239 /// bgez x, label 6240 /// add x, x, 2**k-1 6241 /// label: 6242 /// sra res, x, k 6243 /// neg res, res (when the divisor is negative) 6244 SDValue TargetLowering::buildSDIVPow2WithCMov( 6245 SDNode *N, const APInt &Divisor, SelectionDAG &DAG, 6246 SmallVectorImpl<SDNode *> &Created) const { 6247 unsigned Lg2 = Divisor.countr_zero(); 6248 EVT VT = N->getValueType(0); 6249 6250 SDLoc DL(N); 6251 SDValue N0 = N->getOperand(0); 6252 SDValue Zero = DAG.getConstant(0, DL, VT); 6253 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2); 6254 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT); 6255 6256 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right. 6257 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6258 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT); 6259 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 6260 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 6261 6262 Created.push_back(Cmp.getNode()); 6263 Created.push_back(Add.getNode()); 6264 Created.push_back(CMov.getNode()); 6265 6266 // Divide by pow2. 6267 SDValue SRA = 6268 DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, VT)); 6269 6270 // If we're dividing by a positive value, we're done. Otherwise, we must 6271 // negate the result. 6272 if (Divisor.isNonNegative()) 6273 return SRA; 6274 6275 Created.push_back(SRA.getNode()); 6276 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA); 6277 } 6278 6279 /// Given an ISD::SDIV node expressing a divide by constant, 6280 /// return a DAG expression to select that will generate the same value by 6281 /// multiplying by a magic number. 6282 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6283 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 6284 bool IsAfterLegalization, 6285 bool IsAfterLegalTypes, 6286 SmallVectorImpl<SDNode *> &Created) const { 6287 SDLoc dl(N); 6288 EVT VT = N->getValueType(0); 6289 EVT SVT = VT.getScalarType(); 6290 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6291 EVT ShSVT = ShVT.getScalarType(); 6292 unsigned EltBits = VT.getScalarSizeInBits(); 6293 EVT MulVT; 6294 6295 // Check to see if we can do this. 6296 // FIXME: We should be more aggressive here. 6297 if (!isTypeLegal(VT)) { 6298 // Limit this to simple scalars for now. 6299 if (VT.isVector() || !VT.isSimple()) 6300 return SDValue(); 6301 6302 // If this type will be promoted to a large enough type with a legal 6303 // multiply operation, we can go ahead and do this transform. 6304 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6305 return SDValue(); 6306 6307 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6308 if (MulVT.getSizeInBits() < (2 * EltBits) || 6309 !isOperationLegal(ISD::MUL, MulVT)) 6310 return SDValue(); 6311 } 6312 6313 // If the sdiv has an 'exact' bit we can use a simpler lowering. 6314 if (N->getFlags().hasExact()) 6315 return BuildExactSDIV(*this, N, dl, DAG, Created); 6316 6317 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 6318 6319 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6320 if (C->isZero()) 6321 return false; 6322 6323 const APInt &Divisor = C->getAPIntValue(); 6324 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 6325 int NumeratorFactor = 0; 6326 int ShiftMask = -1; 6327 6328 if (Divisor.isOne() || Divisor.isAllOnes()) { 6329 // If d is +1/-1, we just multiply the numerator by +1/-1. 6330 NumeratorFactor = Divisor.getSExtValue(); 6331 magics.Magic = 0; 6332 magics.ShiftAmount = 0; 6333 ShiftMask = 0; 6334 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 6335 // If d > 0 and m < 0, add the numerator. 6336 NumeratorFactor = 1; 6337 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 6338 // If d < 0 and m > 0, subtract the numerator. 6339 NumeratorFactor = -1; 6340 } 6341 6342 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 6343 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT)); 6344 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 6345 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT)); 6346 return true; 6347 }; 6348 6349 SDValue N0 = N->getOperand(0); 6350 SDValue N1 = N->getOperand(1); 6351 6352 // Collect the shifts / magic values from each element. 6353 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 6354 return SDValue(); 6355 6356 SDValue MagicFactor, Factor, Shift, ShiftMask; 6357 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6358 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6359 Factor = DAG.getBuildVector(VT, dl, Factors); 6360 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6361 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 6362 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6363 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 6364 Shifts.size() == 1 && ShiftMasks.size() == 1 && 6365 "Expected matchUnaryPredicate to return one element for scalable " 6366 "vectors"); 6367 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6368 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6369 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6370 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 6371 } else { 6372 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6373 MagicFactor = MagicFactors[0]; 6374 Factor = Factors[0]; 6375 Shift = Shifts[0]; 6376 ShiftMask = ShiftMasks[0]; 6377 } 6378 6379 // Multiply the numerator (operand 0) by the magic value. 6380 // FIXME: We should support doing a MUL in a wider type. 6381 auto GetMULHS = [&](SDValue X, SDValue Y) { 6382 // If the type isn't legal, use a wider mul of the type calculated 6383 // earlier. 6384 if (!isTypeLegal(VT)) { 6385 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 6386 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 6387 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6388 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6389 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6390 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6391 } 6392 6393 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 6394 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 6395 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 6396 SDValue LoHi = 6397 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6398 return SDValue(LoHi.getNode(), 1); 6399 } 6400 // If type twice as wide legal, widen and use a mul plus a shift. 6401 unsigned Size = VT.getScalarSizeInBits(); 6402 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6403 if (VT.isVector()) 6404 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6405 VT.getVectorElementCount()); 6406 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then 6407 // custom lowered. This is very expensive so avoid it at all costs for 6408 // constant divisors. 6409 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) && 6410 isOperationCustom(ISD::SDIVREM, VT.getScalarType())) || 6411 isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6412 X = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, X); 6413 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, Y); 6414 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6415 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6416 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6417 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6418 } 6419 return SDValue(); 6420 }; 6421 6422 SDValue Q = GetMULHS(N0, MagicFactor); 6423 if (!Q) 6424 return SDValue(); 6425 6426 Created.push_back(Q.getNode()); 6427 6428 // (Optionally) Add/subtract the numerator using Factor. 6429 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 6430 Created.push_back(Factor.getNode()); 6431 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 6432 Created.push_back(Q.getNode()); 6433 6434 // Shift right algebraic by shift value. 6435 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 6436 Created.push_back(Q.getNode()); 6437 6438 // Extract the sign bit, mask it and add it to the quotient. 6439 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 6440 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 6441 Created.push_back(T.getNode()); 6442 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 6443 Created.push_back(T.getNode()); 6444 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 6445 } 6446 6447 /// Given an ISD::UDIV node expressing a divide by constant, 6448 /// return a DAG expression to select that will generate the same value by 6449 /// multiplying by a magic number. 6450 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6451 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 6452 bool IsAfterLegalization, 6453 bool IsAfterLegalTypes, 6454 SmallVectorImpl<SDNode *> &Created) const { 6455 SDLoc dl(N); 6456 EVT VT = N->getValueType(0); 6457 EVT SVT = VT.getScalarType(); 6458 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6459 EVT ShSVT = ShVT.getScalarType(); 6460 unsigned EltBits = VT.getScalarSizeInBits(); 6461 EVT MulVT; 6462 6463 // Check to see if we can do this. 6464 // FIXME: We should be more aggressive here. 6465 if (!isTypeLegal(VT)) { 6466 // Limit this to simple scalars for now. 6467 if (VT.isVector() || !VT.isSimple()) 6468 return SDValue(); 6469 6470 // If this type will be promoted to a large enough type with a legal 6471 // multiply operation, we can go ahead and do this transform. 6472 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6473 return SDValue(); 6474 6475 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6476 if (MulVT.getSizeInBits() < (2 * EltBits) || 6477 !isOperationLegal(ISD::MUL, MulVT)) 6478 return SDValue(); 6479 } 6480 6481 // If the udiv has an 'exact' bit we can use a simpler lowering. 6482 if (N->getFlags().hasExact()) 6483 return BuildExactUDIV(*this, N, dl, DAG, Created); 6484 6485 SDValue N0 = N->getOperand(0); 6486 SDValue N1 = N->getOperand(1); 6487 6488 // Try to use leading zeros of the dividend to reduce the multiplier and 6489 // avoid expensive fixups. 6490 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros(); 6491 6492 bool UseNPQ = false, UsePreShift = false, UsePostShift = false; 6493 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 6494 6495 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 6496 if (C->isZero()) 6497 return false; 6498 const APInt& Divisor = C->getAPIntValue(); 6499 6500 SDValue PreShift, MagicFactor, NPQFactor, PostShift; 6501 6502 // Magic algorithm doesn't work for division by 1. We need to emit a select 6503 // at the end. 6504 if (Divisor.isOne()) { 6505 PreShift = PostShift = DAG.getUNDEF(ShSVT); 6506 MagicFactor = NPQFactor = DAG.getUNDEF(SVT); 6507 } else { 6508 UnsignedDivisionByConstantInfo magics = 6509 UnsignedDivisionByConstantInfo::get( 6510 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero())); 6511 6512 MagicFactor = DAG.getConstant(magics.Magic, dl, SVT); 6513 6514 assert(magics.PreShift < Divisor.getBitWidth() && 6515 "We shouldn't generate an undefined shift!"); 6516 assert(magics.PostShift < Divisor.getBitWidth() && 6517 "We shouldn't generate an undefined shift!"); 6518 assert((!magics.IsAdd || magics.PreShift == 0) && 6519 "Unexpected pre-shift"); 6520 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT); 6521 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT); 6522 NPQFactor = DAG.getConstant( 6523 magics.IsAdd ? APInt::getOneBitSet(EltBits, EltBits - 1) 6524 : APInt::getZero(EltBits), 6525 dl, SVT); 6526 UseNPQ |= magics.IsAdd; 6527 UsePreShift |= magics.PreShift != 0; 6528 UsePostShift |= magics.PostShift != 0; 6529 } 6530 6531 PreShifts.push_back(PreShift); 6532 MagicFactors.push_back(MagicFactor); 6533 NPQFactors.push_back(NPQFactor); 6534 PostShifts.push_back(PostShift); 6535 return true; 6536 }; 6537 6538 // Collect the shifts/magic values from each element. 6539 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 6540 return SDValue(); 6541 6542 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 6543 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6544 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 6545 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6546 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 6547 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 6548 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6549 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 6550 NPQFactors.size() == 1 && PostShifts.size() == 1 && 6551 "Expected matchUnaryPredicate to return one for scalable vectors"); 6552 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 6553 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6554 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 6555 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 6556 } else { 6557 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6558 PreShift = PreShifts[0]; 6559 MagicFactor = MagicFactors[0]; 6560 PostShift = PostShifts[0]; 6561 } 6562 6563 SDValue Q = N0; 6564 if (UsePreShift) { 6565 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 6566 Created.push_back(Q.getNode()); 6567 } 6568 6569 // FIXME: We should support doing a MUL in a wider type. 6570 auto GetMULHU = [&](SDValue X, SDValue Y) { 6571 // If the type isn't legal, use a wider mul of the type calculated 6572 // earlier. 6573 if (!isTypeLegal(VT)) { 6574 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 6575 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 6576 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6577 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6578 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6579 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6580 } 6581 6582 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 6583 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 6584 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 6585 SDValue LoHi = 6586 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6587 return SDValue(LoHi.getNode(), 1); 6588 } 6589 // If type twice as wide legal, widen and use a mul plus a shift. 6590 unsigned Size = VT.getScalarSizeInBits(); 6591 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6592 if (VT.isVector()) 6593 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6594 VT.getVectorElementCount()); 6595 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then 6596 // custom lowered. This is very expensive so avoid it at all costs for 6597 // constant divisors. 6598 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) && 6599 isOperationCustom(ISD::UDIVREM, VT.getScalarType())) || 6600 isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6601 X = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, X); 6602 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, Y); 6603 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6604 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6605 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6606 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6607 } 6608 return SDValue(); // No mulhu or equivalent 6609 }; 6610 6611 // Multiply the numerator (operand 0) by the magic value. 6612 Q = GetMULHU(Q, MagicFactor); 6613 if (!Q) 6614 return SDValue(); 6615 6616 Created.push_back(Q.getNode()); 6617 6618 if (UseNPQ) { 6619 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 6620 Created.push_back(NPQ.getNode()); 6621 6622 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 6623 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 6624 if (VT.isVector()) 6625 NPQ = GetMULHU(NPQ, NPQFactor); 6626 else 6627 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 6628 6629 Created.push_back(NPQ.getNode()); 6630 6631 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 6632 Created.push_back(Q.getNode()); 6633 } 6634 6635 if (UsePostShift) { 6636 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 6637 Created.push_back(Q.getNode()); 6638 } 6639 6640 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6641 6642 SDValue One = DAG.getConstant(1, dl, VT); 6643 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 6644 return DAG.getSelect(dl, VT, IsOne, N0, Q); 6645 } 6646 6647 /// If all values in Values that *don't* match the predicate are same 'splat' 6648 /// value, then replace all values with that splat value. 6649 /// Else, if AlternativeReplacement was provided, then replace all values that 6650 /// do match predicate with AlternativeReplacement value. 6651 static void 6652 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6653 std::function<bool(SDValue)> Predicate, 6654 SDValue AlternativeReplacement = SDValue()) { 6655 SDValue Replacement; 6656 // Is there a value for which the Predicate does *NOT* match? What is it? 6657 auto SplatValue = llvm::find_if_not(Values, Predicate); 6658 if (SplatValue != Values.end()) { 6659 // Does Values consist only of SplatValue's and values matching Predicate? 6660 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6661 return Value == *SplatValue || Predicate(Value); 6662 })) // Then we shall replace values matching predicate with SplatValue. 6663 Replacement = *SplatValue; 6664 } 6665 if (!Replacement) { 6666 // Oops, we did not find the "baseline" splat value. 6667 if (!AlternativeReplacement) 6668 return; // Nothing to do. 6669 // Let's replace with provided value then. 6670 Replacement = AlternativeReplacement; 6671 } 6672 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6673 } 6674 6675 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6676 /// where the divisor is constant and the comparison target is zero, 6677 /// return a DAG expression that will generate the same comparison result 6678 /// using only multiplications, additions and shifts/rotations. 6679 /// Ref: "Hacker's Delight" 10-17. 6680 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6681 SDValue CompTargetNode, 6682 ISD::CondCode Cond, 6683 DAGCombinerInfo &DCI, 6684 const SDLoc &DL) const { 6685 SmallVector<SDNode *, 5> Built; 6686 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6687 DCI, DL, Built)) { 6688 for (SDNode *N : Built) 6689 DCI.AddToWorklist(N); 6690 return Folded; 6691 } 6692 6693 return SDValue(); 6694 } 6695 6696 SDValue 6697 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6698 SDValue CompTargetNode, ISD::CondCode Cond, 6699 DAGCombinerInfo &DCI, const SDLoc &DL, 6700 SmallVectorImpl<SDNode *> &Created) const { 6701 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6702 // - D must be constant, with D = D0 * 2^K where D0 is odd 6703 // - P is the multiplicative inverse of D0 modulo 2^W 6704 // - Q = floor(((2^W) - 1) / D) 6705 // where W is the width of the common type of N and D. 6706 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6707 "Only applicable for (in)equality comparisons."); 6708 6709 SelectionDAG &DAG = DCI.DAG; 6710 6711 EVT VT = REMNode.getValueType(); 6712 EVT SVT = VT.getScalarType(); 6713 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6714 EVT ShSVT = ShVT.getScalarType(); 6715 6716 // If MUL is unavailable, we cannot proceed in any case. 6717 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6718 return SDValue(); 6719 6720 bool ComparingWithAllZeros = true; 6721 bool AllComparisonsWithNonZerosAreTautological = true; 6722 bool HadTautologicalLanes = false; 6723 bool AllLanesAreTautological = true; 6724 bool HadEvenDivisor = false; 6725 bool AllDivisorsArePowerOfTwo = true; 6726 bool HadTautologicalInvertedLanes = false; 6727 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6728 6729 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6730 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6731 if (CDiv->isZero()) 6732 return false; 6733 6734 const APInt &D = CDiv->getAPIntValue(); 6735 const APInt &Cmp = CCmp->getAPIntValue(); 6736 6737 ComparingWithAllZeros &= Cmp.isZero(); 6738 6739 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6740 // if C2 is not less than C1, the comparison is always false. 6741 // But we will only be able to produce the comparison that will give the 6742 // opposive tautological answer. So this lane would need to be fixed up. 6743 bool TautologicalInvertedLane = D.ule(Cmp); 6744 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6745 6746 // If all lanes are tautological (either all divisors are ones, or divisor 6747 // is not greater than the constant we are comparing with), 6748 // we will prefer to avoid the fold. 6749 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6750 HadTautologicalLanes |= TautologicalLane; 6751 AllLanesAreTautological &= TautologicalLane; 6752 6753 // If we are comparing with non-zero, we need'll need to subtract said 6754 // comparison value from the LHS. But there is no point in doing that if 6755 // every lane where we are comparing with non-zero is tautological.. 6756 if (!Cmp.isZero()) 6757 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6758 6759 // Decompose D into D0 * 2^K 6760 unsigned K = D.countr_zero(); 6761 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6762 APInt D0 = D.lshr(K); 6763 6764 // D is even if it has trailing zeros. 6765 HadEvenDivisor |= (K != 0); 6766 // D is a power-of-two if D0 is one. 6767 // If all divisors are power-of-two, we will prefer to avoid the fold. 6768 AllDivisorsArePowerOfTwo &= D0.isOne(); 6769 6770 // P = inv(D0, 2^W) 6771 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6772 unsigned W = D.getBitWidth(); 6773 APInt P = D0.multiplicativeInverse(); 6774 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6775 6776 // Q = floor((2^W - 1) u/ D) 6777 // R = ((2^W - 1) u% D) 6778 APInt Q, R; 6779 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6780 6781 // If we are comparing with zero, then that comparison constant is okay, 6782 // else it may need to be one less than that. 6783 if (Cmp.ugt(R)) 6784 Q -= 1; 6785 6786 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6787 "We are expecting that K is always less than all-ones for ShSVT"); 6788 6789 // If the lane is tautological the result can be constant-folded. 6790 if (TautologicalLane) { 6791 // Set P and K amount to a bogus values so we can try to splat them. 6792 P = 0; 6793 K = -1; 6794 // And ensure that comparison constant is tautological, 6795 // it will always compare true/false. 6796 Q = -1; 6797 } 6798 6799 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6800 KAmts.push_back( 6801 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K, /*isSigned=*/false, 6802 /*implicitTrunc=*/true), 6803 DL, ShSVT)); 6804 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6805 return true; 6806 }; 6807 6808 SDValue N = REMNode.getOperand(0); 6809 SDValue D = REMNode.getOperand(1); 6810 6811 // Collect the values from each element. 6812 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6813 return SDValue(); 6814 6815 // If all lanes are tautological, the result can be constant-folded. 6816 if (AllLanesAreTautological) 6817 return SDValue(); 6818 6819 // If this is a urem by a powers-of-two, avoid the fold since it can be 6820 // best implemented as a bit test. 6821 if (AllDivisorsArePowerOfTwo) 6822 return SDValue(); 6823 6824 SDValue PVal, KVal, QVal; 6825 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6826 if (HadTautologicalLanes) { 6827 // Try to turn PAmts into a splat, since we don't care about the values 6828 // that are currently '0'. If we can't, just keep '0'`s. 6829 turnVectorIntoSplatVector(PAmts, isNullConstant); 6830 // Try to turn KAmts into a splat, since we don't care about the values 6831 // that are currently '-1'. If we can't, change them to '0'`s. 6832 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6833 DAG.getConstant(0, DL, ShSVT)); 6834 } 6835 6836 PVal = DAG.getBuildVector(VT, DL, PAmts); 6837 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6838 QVal = DAG.getBuildVector(VT, DL, QAmts); 6839 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6840 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6841 "Expected matchBinaryPredicate to return one element for " 6842 "SPLAT_VECTORs"); 6843 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6844 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6845 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6846 } else { 6847 PVal = PAmts[0]; 6848 KVal = KAmts[0]; 6849 QVal = QAmts[0]; 6850 } 6851 6852 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6853 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6854 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6855 assert(CompTargetNode.getValueType() == N.getValueType() && 6856 "Expecting that the types on LHS and RHS of comparisons match."); 6857 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6858 } 6859 6860 // (mul N, P) 6861 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6862 Created.push_back(Op0.getNode()); 6863 6864 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6865 // divisors as a performance improvement, since rotating by 0 is a no-op. 6866 if (HadEvenDivisor) { 6867 // We need ROTR to do this. 6868 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6869 return SDValue(); 6870 // UREM: (rotr (mul N, P), K) 6871 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6872 Created.push_back(Op0.getNode()); 6873 } 6874 6875 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6876 SDValue NewCC = 6877 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6878 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6879 if (!HadTautologicalInvertedLanes) 6880 return NewCC; 6881 6882 // If any lanes previously compared always-false, the NewCC will give 6883 // always-true result for them, so we need to fixup those lanes. 6884 // Or the other way around for inequality predicate. 6885 assert(VT.isVector() && "Can/should only get here for vectors."); 6886 Created.push_back(NewCC.getNode()); 6887 6888 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6889 // if C2 is not less than C1, the comparison is always false. 6890 // But we have produced the comparison that will give the 6891 // opposive tautological answer. So these lanes would need to be fixed up. 6892 SDValue TautologicalInvertedChannels = 6893 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6894 Created.push_back(TautologicalInvertedChannels.getNode()); 6895 6896 // NOTE: we avoid letting illegal types through even if we're before legalize 6897 // ops – legalization has a hard time producing good code for this. 6898 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6899 // If we have a vector select, let's replace the comparison results in the 6900 // affected lanes with the correct tautological result. 6901 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6902 DL, SETCCVT, SETCCVT); 6903 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6904 Replacement, NewCC); 6905 } 6906 6907 // Else, we can just invert the comparison result in the appropriate lanes. 6908 // 6909 // NOTE: see the note above VSELECT above. 6910 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6911 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6912 TautologicalInvertedChannels); 6913 6914 return SDValue(); // Don't know how to lower. 6915 } 6916 6917 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6918 /// where the divisor is constant and the comparison target is zero, 6919 /// return a DAG expression that will generate the same comparison result 6920 /// using only multiplications, additions and shifts/rotations. 6921 /// Ref: "Hacker's Delight" 10-17. 6922 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6923 SDValue CompTargetNode, 6924 ISD::CondCode Cond, 6925 DAGCombinerInfo &DCI, 6926 const SDLoc &DL) const { 6927 SmallVector<SDNode *, 7> Built; 6928 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6929 DCI, DL, Built)) { 6930 assert(Built.size() <= 7 && "Max size prediction failed."); 6931 for (SDNode *N : Built) 6932 DCI.AddToWorklist(N); 6933 return Folded; 6934 } 6935 6936 return SDValue(); 6937 } 6938 6939 SDValue 6940 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6941 SDValue CompTargetNode, ISD::CondCode Cond, 6942 DAGCombinerInfo &DCI, const SDLoc &DL, 6943 SmallVectorImpl<SDNode *> &Created) const { 6944 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17. 6945 // Fold: 6946 // (seteq/ne (srem N, D), 0) 6947 // To: 6948 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6949 // 6950 // - D must be constant, with D = D0 * 2^K where D0 is odd 6951 // - P is the multiplicative inverse of D0 modulo 2^W 6952 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6953 // - Q = floor((2 * A) / (2^K)) 6954 // where W is the width of the common type of N and D. 6955 // 6956 // When D is a power of two (and thus D0 is 1), the normal 6957 // formula for A and Q don't apply, because the derivation 6958 // depends on D not dividing 2^(W-1), and thus theorem ZRS 6959 // does not apply. This specifically fails when N = INT_MIN. 6960 // 6961 // Instead, for power-of-two D, we use: 6962 // - A = 2^(W-1) 6963 // |-> Order-preserving map from [-2^(W-1), 2^(W-1) - 1] to [0,2^W - 1]) 6964 // - Q = 2^(W-K) - 1 6965 // |-> Test that the top K bits are zero after rotation 6966 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6967 "Only applicable for (in)equality comparisons."); 6968 6969 SelectionDAG &DAG = DCI.DAG; 6970 6971 EVT VT = REMNode.getValueType(); 6972 EVT SVT = VT.getScalarType(); 6973 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6974 EVT ShSVT = ShVT.getScalarType(); 6975 6976 // If we are after ops legalization, and MUL is unavailable, we can not 6977 // proceed. 6978 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6979 return SDValue(); 6980 6981 // TODO: Could support comparing with non-zero too. 6982 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6983 if (!CompTarget || !CompTarget->isZero()) 6984 return SDValue(); 6985 6986 bool HadIntMinDivisor = false; 6987 bool HadOneDivisor = false; 6988 bool AllDivisorsAreOnes = true; 6989 bool HadEvenDivisor = false; 6990 bool NeedToApplyOffset = false; 6991 bool AllDivisorsArePowerOfTwo = true; 6992 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6993 6994 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6995 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6996 if (C->isZero()) 6997 return false; 6998 6999 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 7000 7001 // WARNING: this fold is only valid for positive divisors! 7002 APInt D = C->getAPIntValue(); 7003 if (D.isNegative()) 7004 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 7005 7006 HadIntMinDivisor |= D.isMinSignedValue(); 7007 7008 // If all divisors are ones, we will prefer to avoid the fold. 7009 HadOneDivisor |= D.isOne(); 7010 AllDivisorsAreOnes &= D.isOne(); 7011 7012 // Decompose D into D0 * 2^K 7013 unsigned K = D.countr_zero(); 7014 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 7015 APInt D0 = D.lshr(K); 7016 7017 if (!D.isMinSignedValue()) { 7018 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 7019 // we don't care about this lane in this fold, we'll special-handle it. 7020 HadEvenDivisor |= (K != 0); 7021 } 7022 7023 // D is a power-of-two if D0 is one. This includes INT_MIN. 7024 // If all divisors are power-of-two, we will prefer to avoid the fold. 7025 AllDivisorsArePowerOfTwo &= D0.isOne(); 7026 7027 // P = inv(D0, 2^W) 7028 // 2^W requires W + 1 bits, so we have to extend and then truncate. 7029 unsigned W = D.getBitWidth(); 7030 APInt P = D0.multiplicativeInverse(); 7031 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 7032 7033 // A = floor((2^(W - 1) - 1) / D0) & -2^K 7034 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 7035 A.clearLowBits(K); 7036 7037 if (!D.isMinSignedValue()) { 7038 // If divisor INT_MIN, then we don't care about this lane in this fold, 7039 // we'll special-handle it. 7040 NeedToApplyOffset |= A != 0; 7041 } 7042 7043 // Q = floor((2 * A) / (2^K)) 7044 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 7045 7046 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 7047 "We are expecting that A is always less than all-ones for SVT"); 7048 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 7049 "We are expecting that K is always less than all-ones for ShSVT"); 7050 7051 // If D was a power of two, apply the alternate constant derivation. 7052 if (D0.isOne()) { 7053 // A = 2^(W-1) 7054 A = APInt::getSignedMinValue(W); 7055 // - Q = 2^(W-K) - 1 7056 Q = APInt::getAllOnes(W - K).zext(W); 7057 } 7058 7059 // If the divisor is 1 the result can be constant-folded. Likewise, we 7060 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 7061 if (D.isOne()) { 7062 // Set P, A and K to a bogus values so we can try to splat them. 7063 P = 0; 7064 A = -1; 7065 K = -1; 7066 7067 // x ?% 1 == 0 <--> true <--> x u<= -1 7068 Q = -1; 7069 } 7070 7071 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 7072 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 7073 KAmts.push_back( 7074 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K, /*isSigned=*/false, 7075 /*implicitTrunc=*/true), 7076 DL, ShSVT)); 7077 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 7078 return true; 7079 }; 7080 7081 SDValue N = REMNode.getOperand(0); 7082 SDValue D = REMNode.getOperand(1); 7083 7084 // Collect the values from each element. 7085 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 7086 return SDValue(); 7087 7088 // If this is a srem by a one, avoid the fold since it can be constant-folded. 7089 if (AllDivisorsAreOnes) 7090 return SDValue(); 7091 7092 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 7093 // since it can be best implemented as a bit test. 7094 if (AllDivisorsArePowerOfTwo) 7095 return SDValue(); 7096 7097 SDValue PVal, AVal, KVal, QVal; 7098 if (D.getOpcode() == ISD::BUILD_VECTOR) { 7099 if (HadOneDivisor) { 7100 // Try to turn PAmts into a splat, since we don't care about the values 7101 // that are currently '0'. If we can't, just keep '0'`s. 7102 turnVectorIntoSplatVector(PAmts, isNullConstant); 7103 // Try to turn AAmts into a splat, since we don't care about the 7104 // values that are currently '-1'. If we can't, change them to '0'`s. 7105 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 7106 DAG.getConstant(0, DL, SVT)); 7107 // Try to turn KAmts into a splat, since we don't care about the values 7108 // that are currently '-1'. If we can't, change them to '0'`s. 7109 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 7110 DAG.getConstant(0, DL, ShSVT)); 7111 } 7112 7113 PVal = DAG.getBuildVector(VT, DL, PAmts); 7114 AVal = DAG.getBuildVector(VT, DL, AAmts); 7115 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 7116 QVal = DAG.getBuildVector(VT, DL, QAmts); 7117 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 7118 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 7119 QAmts.size() == 1 && 7120 "Expected matchUnaryPredicate to return one element for scalable " 7121 "vectors"); 7122 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 7123 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 7124 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 7125 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 7126 } else { 7127 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 7128 PVal = PAmts[0]; 7129 AVal = AAmts[0]; 7130 KVal = KAmts[0]; 7131 QVal = QAmts[0]; 7132 } 7133 7134 // (mul N, P) 7135 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 7136 Created.push_back(Op0.getNode()); 7137 7138 if (NeedToApplyOffset) { 7139 // We need ADD to do this. 7140 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 7141 return SDValue(); 7142 7143 // (add (mul N, P), A) 7144 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 7145 Created.push_back(Op0.getNode()); 7146 } 7147 7148 // Rotate right only if any divisor was even. We avoid rotates for all-odd 7149 // divisors as a performance improvement, since rotating by 0 is a no-op. 7150 if (HadEvenDivisor) { 7151 // We need ROTR to do this. 7152 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 7153 return SDValue(); 7154 // SREM: (rotr (add (mul N, P), A), K) 7155 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 7156 Created.push_back(Op0.getNode()); 7157 } 7158 7159 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 7160 SDValue Fold = 7161 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 7162 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 7163 7164 // If we didn't have lanes with INT_MIN divisor, then we're done. 7165 if (!HadIntMinDivisor) 7166 return Fold; 7167 7168 // That fold is only valid for positive divisors. Which effectively means, 7169 // it is invalid for INT_MIN divisors. So if we have such a lane, 7170 // we must fix-up results for said lanes. 7171 assert(VT.isVector() && "Can/should only get here for vectors."); 7172 7173 // NOTE: we avoid letting illegal types through even if we're before legalize 7174 // ops – legalization has a hard time producing good code for the code that 7175 // follows. 7176 if (!isOperationLegalOrCustom(ISD::SETCC, SETCCVT) || 7177 !isOperationLegalOrCustom(ISD::AND, VT) || 7178 !isCondCodeLegalOrCustom(Cond, VT.getSimpleVT()) || 7179 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 7180 return SDValue(); 7181 7182 Created.push_back(Fold.getNode()); 7183 7184 SDValue IntMin = DAG.getConstant( 7185 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 7186 SDValue IntMax = DAG.getConstant( 7187 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 7188 SDValue Zero = 7189 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 7190 7191 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 7192 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 7193 Created.push_back(DivisorIsIntMin.getNode()); 7194 7195 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 7196 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 7197 Created.push_back(Masked.getNode()); 7198 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 7199 Created.push_back(MaskedIsZero.getNode()); 7200 7201 // To produce final result we need to blend 2 vectors: 'SetCC' and 7202 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 7203 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 7204 // constant-folded, select can get lowered to a shuffle with constant mask. 7205 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 7206 MaskedIsZero, Fold); 7207 7208 return Blended; 7209 } 7210 7211 bool TargetLowering:: 7212 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 7213 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 7214 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 7215 "be a constant integer"); 7216 return true; 7217 } 7218 7219 return false; 7220 } 7221 7222 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7223 const DenormalMode &Mode) const { 7224 SDLoc DL(Op); 7225 EVT VT = Op.getValueType(); 7226 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7227 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7228 7229 // This is specifically a check for the handling of denormal inputs, not the 7230 // result. 7231 if (Mode.Input == DenormalMode::PreserveSign || 7232 Mode.Input == DenormalMode::PositiveZero) { 7233 // Test = X == 0.0 7234 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7235 } 7236 7237 // Testing it with denormal inputs to avoid wrong estimate. 7238 // 7239 // Test = fabs(X) < SmallestNormal 7240 const fltSemantics &FltSem = VT.getFltSemantics(); 7241 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 7242 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 7243 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 7244 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 7245 } 7246 7247 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 7248 bool LegalOps, bool OptForSize, 7249 NegatibleCost &Cost, 7250 unsigned Depth) const { 7251 // fneg is removable even if it has multiple uses. 7252 if (Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::VP_FNEG) { 7253 Cost = NegatibleCost::Cheaper; 7254 return Op.getOperand(0); 7255 } 7256 7257 // Don't recurse exponentially. 7258 if (Depth > SelectionDAG::MaxRecursionDepth) 7259 return SDValue(); 7260 7261 // Pre-increment recursion depth for use in recursive calls. 7262 ++Depth; 7263 const SDNodeFlags Flags = Op->getFlags(); 7264 const TargetOptions &Options = DAG.getTarget().Options; 7265 EVT VT = Op.getValueType(); 7266 unsigned Opcode = Op.getOpcode(); 7267 7268 // Don't allow anything with multiple uses unless we know it is free. 7269 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 7270 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 7271 isFPExtFree(VT, Op.getOperand(0).getValueType()); 7272 if (!IsFreeExtend) 7273 return SDValue(); 7274 } 7275 7276 auto RemoveDeadNode = [&](SDValue N) { 7277 if (N && N.getNode()->use_empty()) 7278 DAG.RemoveDeadNode(N.getNode()); 7279 }; 7280 7281 SDLoc DL(Op); 7282 7283 // Because getNegatedExpression can delete nodes we need a handle to keep 7284 // temporary nodes alive in case the recursion manages to create an identical 7285 // node. 7286 std::list<HandleSDNode> Handles; 7287 7288 switch (Opcode) { 7289 case ISD::ConstantFP: { 7290 // Don't invert constant FP values after legalization unless the target says 7291 // the negated constant is legal. 7292 bool IsOpLegal = 7293 isOperationLegal(ISD::ConstantFP, VT) || 7294 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 7295 OptForSize); 7296 7297 if (LegalOps && !IsOpLegal) 7298 break; 7299 7300 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 7301 V.changeSign(); 7302 SDValue CFP = DAG.getConstantFP(V, DL, VT); 7303 7304 // If we already have the use of the negated floating constant, it is free 7305 // to negate it even it has multiple uses. 7306 if (!Op.hasOneUse() && CFP.use_empty()) 7307 break; 7308 Cost = NegatibleCost::Neutral; 7309 return CFP; 7310 } 7311 case ISD::BUILD_VECTOR: { 7312 // Only permit BUILD_VECTOR of constants. 7313 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 7314 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 7315 })) 7316 break; 7317 7318 bool IsOpLegal = 7319 (isOperationLegal(ISD::ConstantFP, VT) && 7320 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 7321 llvm::all_of(Op->op_values(), [&](SDValue N) { 7322 return N.isUndef() || 7323 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 7324 OptForSize); 7325 }); 7326 7327 if (LegalOps && !IsOpLegal) 7328 break; 7329 7330 SmallVector<SDValue, 4> Ops; 7331 for (SDValue C : Op->op_values()) { 7332 if (C.isUndef()) { 7333 Ops.push_back(C); 7334 continue; 7335 } 7336 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 7337 V.changeSign(); 7338 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 7339 } 7340 Cost = NegatibleCost::Neutral; 7341 return DAG.getBuildVector(VT, DL, Ops); 7342 } 7343 case ISD::FADD: { 7344 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7345 break; 7346 7347 // After operation legalization, it might not be legal to create new FSUBs. 7348 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 7349 break; 7350 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7351 7352 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 7353 NegatibleCost CostX = NegatibleCost::Expensive; 7354 SDValue NegX = 7355 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7356 // Prevent this node from being deleted by the next call. 7357 if (NegX) 7358 Handles.emplace_back(NegX); 7359 7360 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 7361 NegatibleCost CostY = NegatibleCost::Expensive; 7362 SDValue NegY = 7363 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7364 7365 // We're done with the handles. 7366 Handles.clear(); 7367 7368 // Negate the X if its cost is less or equal than Y. 7369 if (NegX && (CostX <= CostY)) { 7370 Cost = CostX; 7371 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 7372 if (NegY != N) 7373 RemoveDeadNode(NegY); 7374 return N; 7375 } 7376 7377 // Negate the Y if it is not expensive. 7378 if (NegY) { 7379 Cost = CostY; 7380 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 7381 if (NegX != N) 7382 RemoveDeadNode(NegX); 7383 return N; 7384 } 7385 break; 7386 } 7387 case ISD::FSUB: { 7388 // We can't turn -(A-B) into B-A when we honor signed zeros. 7389 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7390 break; 7391 7392 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7393 // fold (fneg (fsub 0, Y)) -> Y 7394 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 7395 if (C->isZero()) { 7396 Cost = NegatibleCost::Cheaper; 7397 return Y; 7398 } 7399 7400 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 7401 Cost = NegatibleCost::Neutral; 7402 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 7403 } 7404 case ISD::FMUL: 7405 case ISD::FDIV: { 7406 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7407 7408 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 7409 NegatibleCost CostX = NegatibleCost::Expensive; 7410 SDValue NegX = 7411 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7412 // Prevent this node from being deleted by the next call. 7413 if (NegX) 7414 Handles.emplace_back(NegX); 7415 7416 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 7417 NegatibleCost CostY = NegatibleCost::Expensive; 7418 SDValue NegY = 7419 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7420 7421 // We're done with the handles. 7422 Handles.clear(); 7423 7424 // Negate the X if its cost is less or equal than Y. 7425 if (NegX && (CostX <= CostY)) { 7426 Cost = CostX; 7427 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 7428 if (NegY != N) 7429 RemoveDeadNode(NegY); 7430 return N; 7431 } 7432 7433 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 7434 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 7435 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 7436 break; 7437 7438 // Negate the Y if it is not expensive. 7439 if (NegY) { 7440 Cost = CostY; 7441 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 7442 if (NegX != N) 7443 RemoveDeadNode(NegX); 7444 return N; 7445 } 7446 break; 7447 } 7448 case ISD::FMA: 7449 case ISD::FMAD: { 7450 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7451 break; 7452 7453 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 7454 NegatibleCost CostZ = NegatibleCost::Expensive; 7455 SDValue NegZ = 7456 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 7457 // Give up if fail to negate the Z. 7458 if (!NegZ) 7459 break; 7460 7461 // Prevent this node from being deleted by the next two calls. 7462 Handles.emplace_back(NegZ); 7463 7464 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 7465 NegatibleCost CostX = NegatibleCost::Expensive; 7466 SDValue NegX = 7467 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7468 // Prevent this node from being deleted by the next call. 7469 if (NegX) 7470 Handles.emplace_back(NegX); 7471 7472 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 7473 NegatibleCost CostY = NegatibleCost::Expensive; 7474 SDValue NegY = 7475 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7476 7477 // We're done with the handles. 7478 Handles.clear(); 7479 7480 // Negate the X if its cost is less or equal than Y. 7481 if (NegX && (CostX <= CostY)) { 7482 Cost = std::min(CostX, CostZ); 7483 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 7484 if (NegY != N) 7485 RemoveDeadNode(NegY); 7486 return N; 7487 } 7488 7489 // Negate the Y if it is not expensive. 7490 if (NegY) { 7491 Cost = std::min(CostY, CostZ); 7492 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 7493 if (NegX != N) 7494 RemoveDeadNode(NegX); 7495 return N; 7496 } 7497 break; 7498 } 7499 7500 case ISD::FP_EXTEND: 7501 case ISD::FSIN: 7502 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7503 OptForSize, Cost, Depth)) 7504 return DAG.getNode(Opcode, DL, VT, NegV); 7505 break; 7506 case ISD::FP_ROUND: 7507 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7508 OptForSize, Cost, Depth)) 7509 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 7510 break; 7511 case ISD::SELECT: 7512 case ISD::VSELECT: { 7513 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS)) 7514 // iff at least one cost is cheaper and the other is neutral/cheaper 7515 SDValue LHS = Op.getOperand(1); 7516 NegatibleCost CostLHS = NegatibleCost::Expensive; 7517 SDValue NegLHS = 7518 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth); 7519 if (!NegLHS || CostLHS > NegatibleCost::Neutral) { 7520 RemoveDeadNode(NegLHS); 7521 break; 7522 } 7523 7524 // Prevent this node from being deleted by the next call. 7525 Handles.emplace_back(NegLHS); 7526 7527 SDValue RHS = Op.getOperand(2); 7528 NegatibleCost CostRHS = NegatibleCost::Expensive; 7529 SDValue NegRHS = 7530 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth); 7531 7532 // We're done with the handles. 7533 Handles.clear(); 7534 7535 if (!NegRHS || CostRHS > NegatibleCost::Neutral || 7536 (CostLHS != NegatibleCost::Cheaper && 7537 CostRHS != NegatibleCost::Cheaper)) { 7538 RemoveDeadNode(NegLHS); 7539 RemoveDeadNode(NegRHS); 7540 break; 7541 } 7542 7543 Cost = std::min(CostLHS, CostRHS); 7544 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS); 7545 } 7546 } 7547 7548 return SDValue(); 7549 } 7550 7551 //===----------------------------------------------------------------------===// 7552 // Legalization Utilities 7553 //===----------------------------------------------------------------------===// 7554 7555 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 7556 SDValue LHS, SDValue RHS, 7557 SmallVectorImpl<SDValue> &Result, 7558 EVT HiLoVT, SelectionDAG &DAG, 7559 MulExpansionKind Kind, SDValue LL, 7560 SDValue LH, SDValue RL, SDValue RH) const { 7561 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 7562 Opcode == ISD::SMUL_LOHI); 7563 7564 bool HasMULHS = (Kind == MulExpansionKind::Always) || 7565 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 7566 bool HasMULHU = (Kind == MulExpansionKind::Always) || 7567 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 7568 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 7569 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 7570 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 7571 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 7572 7573 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 7574 return false; 7575 7576 unsigned OuterBitSize = VT.getScalarSizeInBits(); 7577 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 7578 7579 // LL, LH, RL, and RH must be either all NULL or all set to a value. 7580 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 7581 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 7582 7583 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 7584 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 7585 bool Signed) -> bool { 7586 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 7587 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 7588 Hi = SDValue(Lo.getNode(), 1); 7589 return true; 7590 } 7591 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 7592 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 7593 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 7594 return true; 7595 } 7596 return false; 7597 }; 7598 7599 SDValue Lo, Hi; 7600 7601 if (!LL.getNode() && !RL.getNode() && 7602 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7603 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 7604 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 7605 } 7606 7607 if (!LL.getNode()) 7608 return false; 7609 7610 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 7611 if (DAG.MaskedValueIsZero(LHS, HighMask) && 7612 DAG.MaskedValueIsZero(RHS, HighMask)) { 7613 // The inputs are both zero-extended. 7614 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 7615 Result.push_back(Lo); 7616 Result.push_back(Hi); 7617 if (Opcode != ISD::MUL) { 7618 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7619 Result.push_back(Zero); 7620 Result.push_back(Zero); 7621 } 7622 return true; 7623 } 7624 } 7625 7626 if (!VT.isVector() && Opcode == ISD::MUL && 7627 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize && 7628 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) { 7629 // The input values are both sign-extended. 7630 // TODO non-MUL case? 7631 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 7632 Result.push_back(Lo); 7633 Result.push_back(Hi); 7634 return true; 7635 } 7636 } 7637 7638 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 7639 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl); 7640 7641 if (!LH.getNode() && !RH.getNode() && 7642 isOperationLegalOrCustom(ISD::SRL, VT) && 7643 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7644 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 7645 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 7646 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 7647 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 7648 } 7649 7650 if (!LH.getNode()) 7651 return false; 7652 7653 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 7654 return false; 7655 7656 Result.push_back(Lo); 7657 7658 if (Opcode == ISD::MUL) { 7659 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 7660 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 7661 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 7662 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 7663 Result.push_back(Hi); 7664 return true; 7665 } 7666 7667 // Compute the full width result. 7668 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 7669 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 7670 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7671 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 7672 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 7673 }; 7674 7675 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7676 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 7677 return false; 7678 7679 // This is effectively the add part of a multiply-add of half-sized operands, 7680 // so it cannot overflow. 7681 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7682 7683 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 7684 return false; 7685 7686 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7687 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7688 7689 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 7690 isOperationLegalOrCustom(ISD::ADDE, VT)); 7691 if (UseGlue) 7692 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 7693 Merge(Lo, Hi)); 7694 else 7695 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next, 7696 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 7697 7698 SDValue Carry = Next.getValue(1); 7699 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7700 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7701 7702 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7703 return false; 7704 7705 if (UseGlue) 7706 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7707 Carry); 7708 else 7709 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7710 Zero, Carry); 7711 7712 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7713 7714 if (Opcode == ISD::SMUL_LOHI) { 7715 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7716 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7717 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7718 7719 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7720 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7721 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7722 } 7723 7724 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7725 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7726 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7727 return true; 7728 } 7729 7730 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7731 SelectionDAG &DAG, MulExpansionKind Kind, 7732 SDValue LL, SDValue LH, SDValue RL, 7733 SDValue RH) const { 7734 SmallVector<SDValue, 2> Result; 7735 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7736 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7737 DAG, Kind, LL, LH, RL, RH); 7738 if (Ok) { 7739 assert(Result.size() == 2); 7740 Lo = Result[0]; 7741 Hi = Result[1]; 7742 } 7743 return Ok; 7744 } 7745 7746 // Optimize unsigned division or remainder by constants for types twice as large 7747 // as a legal VT. 7748 // 7749 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder 7750 // can be computed 7751 // as: 7752 // Sum += __builtin_uadd_overflow(Lo, High, &Sum); 7753 // Remainder = Sum % Constant 7754 // This is based on "Remainder by Summing Digits" from Hacker's Delight. 7755 // 7756 // For division, we can compute the remainder using the algorithm described 7757 // above, subtract it from the dividend to get an exact multiple of Constant. 7758 // Then multiply that exact multiply by the multiplicative inverse modulo 7759 // (1 << (BitWidth / 2)) to get the quotient. 7760 7761 // If Constant is even, we can shift right the dividend and the divisor by the 7762 // number of trailing zeros in Constant before applying the remainder algorithm. 7763 // If we're after the quotient, we can subtract this value from the shifted 7764 // dividend and multiply by the multiplicative inverse of the shifted divisor. 7765 // If we want the remainder, we shift the value left by the number of trailing 7766 // zeros and add the bits that were shifted out of the dividend. 7767 bool TargetLowering::expandDIVREMByConstant(SDNode *N, 7768 SmallVectorImpl<SDValue> &Result, 7769 EVT HiLoVT, SelectionDAG &DAG, 7770 SDValue LL, SDValue LH) const { 7771 unsigned Opcode = N->getOpcode(); 7772 EVT VT = N->getValueType(0); 7773 7774 // TODO: Support signed division/remainder. 7775 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM) 7776 return false; 7777 assert( 7778 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) && 7779 "Unexpected opcode"); 7780 7781 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7782 if (!CN) 7783 return false; 7784 7785 APInt Divisor = CN->getAPIntValue(); 7786 unsigned BitWidth = Divisor.getBitWidth(); 7787 unsigned HBitWidth = BitWidth / 2; 7788 assert(VT.getScalarSizeInBits() == BitWidth && 7789 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs"); 7790 7791 // Divisor needs to less than (1 << HBitWidth). 7792 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth); 7793 if (Divisor.uge(HalfMaxPlus1)) 7794 return false; 7795 7796 // We depend on the UREM by constant optimization in DAGCombiner that requires 7797 // high multiply. 7798 if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) && 7799 !isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT)) 7800 return false; 7801 7802 // Don't expand if optimizing for size. 7803 if (DAG.shouldOptForSize()) 7804 return false; 7805 7806 // Early out for 0 or 1 divisors. 7807 if (Divisor.ule(1)) 7808 return false; 7809 7810 // If the divisor is even, shift it until it becomes odd. 7811 unsigned TrailingZeros = 0; 7812 if (!Divisor[0]) { 7813 TrailingZeros = Divisor.countr_zero(); 7814 Divisor.lshrInPlace(TrailingZeros); 7815 } 7816 7817 SDLoc dl(N); 7818 SDValue Sum; 7819 SDValue PartialRem; 7820 7821 // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and 7822 // then add in the carry. 7823 // TODO: If we can't split it in half, we might be able to split into 3 or 7824 // more pieces using a smaller bit width. 7825 if (HalfMaxPlus1.urem(Divisor).isOne()) { 7826 assert(!LL == !LH && "Expected both input halves or no input halves!"); 7827 if (!LL) 7828 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT); 7829 7830 // Shift the input by the number of TrailingZeros in the divisor. The 7831 // shifted out bits will be added to the remainder later. 7832 if (TrailingZeros) { 7833 // Save the shifted off bits if we need the remainder. 7834 if (Opcode != ISD::UDIV) { 7835 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7836 PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL, 7837 DAG.getConstant(Mask, dl, HiLoVT)); 7838 } 7839 7840 LL = DAG.getNode( 7841 ISD::OR, dl, HiLoVT, 7842 DAG.getNode(ISD::SRL, dl, HiLoVT, LL, 7843 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)), 7844 DAG.getNode(ISD::SHL, dl, HiLoVT, LH, 7845 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, 7846 HiLoVT, dl))); 7847 LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH, 7848 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7849 } 7850 7851 // Use uaddo_carry if we can, otherwise use a compare to detect overflow. 7852 EVT SetCCType = 7853 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT); 7854 if (isOperationLegalOrCustom(ISD::UADDO_CARRY, HiLoVT)) { 7855 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType); 7856 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH); 7857 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum, 7858 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1)); 7859 } else { 7860 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH); 7861 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT); 7862 // If the boolean for the target is 0 or 1, we can add the setcc result 7863 // directly. 7864 if (getBooleanContents(HiLoVT) == 7865 TargetLoweringBase::ZeroOrOneBooleanContent) 7866 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT); 7867 else 7868 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT), 7869 DAG.getConstant(0, dl, HiLoVT)); 7870 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry); 7871 } 7872 } 7873 7874 // If we didn't find a sum, we can't do the expansion. 7875 if (!Sum) 7876 return false; 7877 7878 // Perform a HiLoVT urem on the Sum using truncated divisor. 7879 SDValue RemL = 7880 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum, 7881 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT)); 7882 SDValue RemH = DAG.getConstant(0, dl, HiLoVT); 7883 7884 if (Opcode != ISD::UREM) { 7885 // Subtract the remainder from the shifted dividend. 7886 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH); 7887 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH); 7888 7889 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem); 7890 7891 // Multiply by the multiplicative inverse of the divisor modulo 7892 // (1 << BitWidth). 7893 APInt MulFactor = Divisor.multiplicativeInverse(); 7894 7895 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend, 7896 DAG.getConstant(MulFactor, dl, VT)); 7897 7898 // Split the quotient into low and high parts. 7899 SDValue QuotL, QuotH; 7900 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT); 7901 Result.push_back(QuotL); 7902 Result.push_back(QuotH); 7903 } 7904 7905 if (Opcode != ISD::UDIV) { 7906 // If we shifted the input, shift the remainder left and add the bits we 7907 // shifted off the input. 7908 if (TrailingZeros) { 7909 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7910 RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL, 7911 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7912 RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem); 7913 } 7914 Result.push_back(RemL); 7915 Result.push_back(DAG.getConstant(0, dl, HiLoVT)); 7916 } 7917 7918 return true; 7919 } 7920 7921 // Check that (every element of) Z is undef or not an exact multiple of BW. 7922 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7923 return ISD::matchUnaryPredicate( 7924 Z, 7925 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7926 true); 7927 } 7928 7929 static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG) { 7930 EVT VT = Node->getValueType(0); 7931 SDValue ShX, ShY; 7932 SDValue ShAmt, InvShAmt; 7933 SDValue X = Node->getOperand(0); 7934 SDValue Y = Node->getOperand(1); 7935 SDValue Z = Node->getOperand(2); 7936 SDValue Mask = Node->getOperand(3); 7937 SDValue VL = Node->getOperand(4); 7938 7939 unsigned BW = VT.getScalarSizeInBits(); 7940 bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL; 7941 SDLoc DL(SDValue(Node, 0)); 7942 7943 EVT ShVT = Z.getValueType(); 7944 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7945 // fshl: X << C | Y >> (BW - C) 7946 // fshr: X << (BW - C) | Y >> C 7947 // where C = Z % BW is not zero 7948 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7949 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7950 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL); 7951 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask, 7952 VL); 7953 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask, 7954 VL); 7955 } else { 7956 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7957 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7958 SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT); 7959 if (isPowerOf2_32(BW)) { 7960 // Z % BW -> Z & (BW - 1) 7961 ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL); 7962 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7963 SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z, 7964 DAG.getAllOnesConstant(DL, ShVT), Mask, VL); 7965 InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL); 7966 } else { 7967 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7968 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7969 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL); 7970 } 7971 7972 SDValue One = DAG.getConstant(1, DL, ShVT); 7973 if (IsFSHL) { 7974 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL); 7975 SDValue ShY1 = DAG.getNode(ISD::VP_SRL, DL, VT, Y, One, Mask, VL); 7976 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, ShY1, InvShAmt, Mask, VL); 7977 } else { 7978 SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL); 7979 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL); 7980 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, ShAmt, Mask, VL); 7981 } 7982 } 7983 return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL); 7984 } 7985 7986 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7987 SelectionDAG &DAG) const { 7988 if (Node->isVPOpcode()) 7989 return expandVPFunnelShift(Node, DAG); 7990 7991 EVT VT = Node->getValueType(0); 7992 7993 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7994 !isOperationLegalOrCustom(ISD::SRL, VT) || 7995 !isOperationLegalOrCustom(ISD::SUB, VT) || 7996 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7997 return SDValue(); 7998 7999 SDValue X = Node->getOperand(0); 8000 SDValue Y = Node->getOperand(1); 8001 SDValue Z = Node->getOperand(2); 8002 8003 unsigned BW = VT.getScalarSizeInBits(); 8004 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 8005 SDLoc DL(SDValue(Node, 0)); 8006 8007 EVT ShVT = Z.getValueType(); 8008 8009 // If a funnel shift in the other direction is more supported, use it. 8010 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 8011 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 8012 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 8013 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 8014 // fshl X, Y, Z -> fshr X, Y, -Z 8015 // fshr X, Y, Z -> fshl X, Y, -Z 8016 SDValue Zero = DAG.getConstant(0, DL, ShVT); 8017 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 8018 } else { 8019 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 8020 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 8021 SDValue One = DAG.getConstant(1, DL, ShVT); 8022 if (IsFSHL) { 8023 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 8024 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 8025 } else { 8026 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 8027 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 8028 } 8029 Z = DAG.getNOT(DL, Z, ShVT); 8030 } 8031 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 8032 } 8033 8034 SDValue ShX, ShY; 8035 SDValue ShAmt, InvShAmt; 8036 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 8037 // fshl: X << C | Y >> (BW - C) 8038 // fshr: X << (BW - C) | Y >> C 8039 // where C = Z % BW is not zero 8040 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 8041 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 8042 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 8043 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 8044 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 8045 } else { 8046 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 8047 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 8048 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 8049 if (isPowerOf2_32(BW)) { 8050 // Z % BW -> Z & (BW - 1) 8051 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 8052 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 8053 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 8054 } else { 8055 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 8056 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 8057 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 8058 } 8059 8060 SDValue One = DAG.getConstant(1, DL, ShVT); 8061 if (IsFSHL) { 8062 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 8063 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 8064 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 8065 } else { 8066 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 8067 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 8068 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 8069 } 8070 } 8071 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 8072 } 8073 8074 // TODO: Merge with expandFunnelShift. 8075 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 8076 SelectionDAG &DAG) const { 8077 EVT VT = Node->getValueType(0); 8078 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 8079 bool IsLeft = Node->getOpcode() == ISD::ROTL; 8080 SDValue Op0 = Node->getOperand(0); 8081 SDValue Op1 = Node->getOperand(1); 8082 SDLoc DL(SDValue(Node, 0)); 8083 8084 EVT ShVT = Op1.getValueType(); 8085 SDValue Zero = DAG.getConstant(0, DL, ShVT); 8086 8087 // If a rotate in the other direction is more supported, use it. 8088 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 8089 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 8090 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 8091 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 8092 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 8093 } 8094 8095 if (!AllowVectorOps && VT.isVector() && 8096 (!isOperationLegalOrCustom(ISD::SHL, VT) || 8097 !isOperationLegalOrCustom(ISD::SRL, VT) || 8098 !isOperationLegalOrCustom(ISD::SUB, VT) || 8099 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 8100 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 8101 return SDValue(); 8102 8103 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 8104 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 8105 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 8106 SDValue ShVal; 8107 SDValue HsVal; 8108 if (isPowerOf2_32(EltSizeInBits)) { 8109 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 8110 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 8111 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 8112 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 8113 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 8114 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 8115 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 8116 } else { 8117 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 8118 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 8119 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 8120 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 8121 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 8122 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 8123 SDValue One = DAG.getConstant(1, DL, ShVT); 8124 HsVal = 8125 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 8126 } 8127 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 8128 } 8129 8130 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 8131 SelectionDAG &DAG) const { 8132 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 8133 EVT VT = Node->getValueType(0); 8134 unsigned VTBits = VT.getScalarSizeInBits(); 8135 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 8136 8137 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 8138 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 8139 SDValue ShOpLo = Node->getOperand(0); 8140 SDValue ShOpHi = Node->getOperand(1); 8141 SDValue ShAmt = Node->getOperand(2); 8142 EVT ShAmtVT = ShAmt.getValueType(); 8143 EVT ShAmtCCVT = 8144 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 8145 SDLoc dl(Node); 8146 8147 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 8148 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 8149 // away during isel. 8150 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 8151 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 8152 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 8153 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 8154 : DAG.getConstant(0, dl, VT); 8155 8156 SDValue Tmp2, Tmp3; 8157 if (IsSHL) { 8158 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 8159 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 8160 } else { 8161 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 8162 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 8163 } 8164 8165 // If the shift amount is larger or equal than the width of a part we don't 8166 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 8167 // values for large shift amounts. 8168 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 8169 DAG.getConstant(VTBits, dl, ShAmtVT)); 8170 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 8171 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 8172 8173 if (IsSHL) { 8174 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8175 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8176 } else { 8177 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8178 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8179 } 8180 } 8181 8182 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 8183 SelectionDAG &DAG) const { 8184 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8185 SDValue Src = Node->getOperand(OpNo); 8186 EVT SrcVT = Src.getValueType(); 8187 EVT DstVT = Node->getValueType(0); 8188 SDLoc dl(SDValue(Node, 0)); 8189 8190 // FIXME: Only f32 to i64 conversions are supported. 8191 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 8192 return false; 8193 8194 if (Node->isStrictFPOpcode()) 8195 // When a NaN is converted to an integer a trap is allowed. We can't 8196 // use this expansion here because it would eliminate that trap. Other 8197 // traps are also allowed and cannot be eliminated. See 8198 // IEEE 754-2008 sec 5.8. 8199 return false; 8200 8201 // Expand f32 -> i64 conversion 8202 // This algorithm comes from compiler-rt's implementation of fixsfdi: 8203 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 8204 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 8205 EVT IntVT = SrcVT.changeTypeToInteger(); 8206 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 8207 8208 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 8209 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 8210 SDValue Bias = DAG.getConstant(127, dl, IntVT); 8211 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 8212 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 8213 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 8214 8215 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 8216 8217 SDValue ExponentBits = DAG.getNode( 8218 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 8219 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 8220 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 8221 8222 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 8223 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 8224 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 8225 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 8226 8227 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 8228 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 8229 DAG.getConstant(0x00800000, dl, IntVT)); 8230 8231 R = DAG.getZExtOrTrunc(R, dl, DstVT); 8232 8233 R = DAG.getSelectCC( 8234 dl, Exponent, ExponentLoBit, 8235 DAG.getNode(ISD::SHL, dl, DstVT, R, 8236 DAG.getZExtOrTrunc( 8237 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 8238 dl, IntShVT)), 8239 DAG.getNode(ISD::SRL, dl, DstVT, R, 8240 DAG.getZExtOrTrunc( 8241 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 8242 dl, IntShVT)), 8243 ISD::SETGT); 8244 8245 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 8246 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 8247 8248 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 8249 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 8250 return true; 8251 } 8252 8253 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 8254 SDValue &Chain, 8255 SelectionDAG &DAG) const { 8256 SDLoc dl(SDValue(Node, 0)); 8257 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8258 SDValue Src = Node->getOperand(OpNo); 8259 8260 EVT SrcVT = Src.getValueType(); 8261 EVT DstVT = Node->getValueType(0); 8262 EVT SetCCVT = 8263 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8264 EVT DstSetCCVT = 8265 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8266 8267 // Only expand vector types if we have the appropriate vector bit operations. 8268 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 8269 ISD::FP_TO_SINT; 8270 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 8271 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 8272 return false; 8273 8274 // If the maximum float value is smaller then the signed integer range, 8275 // the destination signmask can't be represented by the float, so we can 8276 // just use FP_TO_SINT directly. 8277 const fltSemantics &APFSem = SrcVT.getFltSemantics(); 8278 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 8279 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 8280 if (APFloat::opOverflow & 8281 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 8282 if (Node->isStrictFPOpcode()) { 8283 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8284 { Node->getOperand(0), Src }); 8285 Chain = Result.getValue(1); 8286 } else 8287 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8288 return true; 8289 } 8290 8291 // Don't expand it if there isn't cheap fsub instruction. 8292 if (!isOperationLegalOrCustom( 8293 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 8294 return false; 8295 8296 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8297 SDValue Sel; 8298 8299 if (Node->isStrictFPOpcode()) { 8300 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8301 Node->getOperand(0), /*IsSignaling*/ true); 8302 Chain = Sel.getValue(1); 8303 } else { 8304 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 8305 } 8306 8307 bool Strict = Node->isStrictFPOpcode() || 8308 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 8309 8310 if (Strict) { 8311 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 8312 // signmask then offset (the result of which should be fully representable). 8313 // Sel = Src < 0x8000000000000000 8314 // FltOfs = select Sel, 0, 0x8000000000000000 8315 // IntOfs = select Sel, 0, 0x8000000000000000 8316 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8317 8318 // TODO: Should any fast-math-flags be set for the FSUB? 8319 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 8320 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8321 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8322 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 8323 DAG.getConstant(0, dl, DstVT), 8324 DAG.getConstant(SignMask, dl, DstVT)); 8325 SDValue SInt; 8326 if (Node->isStrictFPOpcode()) { 8327 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 8328 { Chain, Src, FltOfs }); 8329 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8330 { Val.getValue(1), Val }); 8331 Chain = SInt.getValue(1); 8332 } else { 8333 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 8334 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 8335 } 8336 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8337 } else { 8338 // Expand based on maximum range of FP_TO_SINT: 8339 // True = fp_to_sint(Src) 8340 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 8341 // Result = select (Src < 0x8000000000000000), True, False 8342 8343 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8344 // TODO: Should any fast-math-flags be set for the FSUB? 8345 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 8346 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 8347 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 8348 DAG.getConstant(SignMask, dl, DstVT)); 8349 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8350 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 8351 } 8352 return true; 8353 } 8354 8355 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 8356 SDValue &Chain, SelectionDAG &DAG) const { 8357 // This transform is not correct for converting 0 when rounding mode is set 8358 // to round toward negative infinity which will produce -0.0. So disable 8359 // under strictfp. 8360 if (Node->isStrictFPOpcode()) 8361 return false; 8362 8363 SDValue Src = Node->getOperand(0); 8364 EVT SrcVT = Src.getValueType(); 8365 EVT DstVT = Node->getValueType(0); 8366 8367 // If the input is known to be non-negative and SINT_TO_FP is legal then use 8368 // it. 8369 if (Node->getFlags().hasNonNeg() && 8370 isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT)) { 8371 Result = 8372 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0)); 8373 return true; 8374 } 8375 8376 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 8377 return false; 8378 8379 // Only expand vector types if we have the appropriate vector bit 8380 // operations. 8381 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 8382 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 8383 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 8384 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 8385 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 8386 return false; 8387 8388 SDLoc dl(SDValue(Node, 0)); 8389 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 8390 8391 // Implementation of unsigned i64 to f64 following the algorithm in 8392 // __floatundidf in compiler_rt. This implementation performs rounding 8393 // correctly in all rounding modes with the exception of converting 0 8394 // when rounding toward negative infinity. In that case the fsub will 8395 // produce -0.0. This will be added to +0.0 and produce -0.0 which is 8396 // incorrect. 8397 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 8398 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 8399 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT); 8400 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 8401 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 8402 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 8403 8404 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 8405 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 8406 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 8407 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 8408 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 8409 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 8410 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 8411 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 8412 return true; 8413 } 8414 8415 SDValue 8416 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 8417 SelectionDAG &DAG) const { 8418 unsigned Opcode = Node->getOpcode(); 8419 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 8420 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 8421 "Wrong opcode"); 8422 8423 if (Node->getFlags().hasNoNaNs()) { 8424 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 8425 EVT VT = Node->getValueType(0); 8426 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) || 8427 !isOperationLegalOrCustom(ISD::VSELECT, VT)) && 8428 VT.isVector()) 8429 return SDValue(); 8430 SDValue Op1 = Node->getOperand(0); 8431 SDValue Op2 = Node->getOperand(1); 8432 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 8433 // Copy FMF flags, but always set the no-signed-zeros flag 8434 // as this is implied by the FMINNUM/FMAXNUM semantics. 8435 SelCC->setFlags(Node->getFlags() | SDNodeFlags::NoSignedZeros); 8436 return SelCC; 8437 } 8438 8439 return SDValue(); 8440 } 8441 8442 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 8443 SelectionDAG &DAG) const { 8444 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG)) 8445 return Expanded; 8446 8447 EVT VT = Node->getValueType(0); 8448 if (VT.isScalableVector()) 8449 report_fatal_error( 8450 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 8451 8452 SDLoc dl(Node); 8453 unsigned NewOp = 8454 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 8455 8456 if (isOperationLegalOrCustom(NewOp, VT)) { 8457 SDValue Quiet0 = Node->getOperand(0); 8458 SDValue Quiet1 = Node->getOperand(1); 8459 8460 if (!Node->getFlags().hasNoNaNs()) { 8461 // Insert canonicalizes if it's possible we need to quiet to get correct 8462 // sNaN behavior. 8463 if (!DAG.isKnownNeverSNaN(Quiet0)) { 8464 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 8465 Node->getFlags()); 8466 } 8467 if (!DAG.isKnownNeverSNaN(Quiet1)) { 8468 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 8469 Node->getFlags()); 8470 } 8471 } 8472 8473 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 8474 } 8475 8476 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 8477 // instead if there are no NaNs and there can't be an incompatible zero 8478 // compare: at least one operand isn't +/-0, or there are no signed-zeros. 8479 if ((Node->getFlags().hasNoNaNs() || 8480 (DAG.isKnownNeverNaN(Node->getOperand(0)) && 8481 DAG.isKnownNeverNaN(Node->getOperand(1)))) && 8482 (Node->getFlags().hasNoSignedZeros() || 8483 DAG.isKnownNeverZeroFloat(Node->getOperand(0)) || 8484 DAG.isKnownNeverZeroFloat(Node->getOperand(1)))) { 8485 unsigned IEEE2018Op = 8486 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 8487 if (isOperationLegalOrCustom(IEEE2018Op, VT)) 8488 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 8489 Node->getOperand(1), Node->getFlags()); 8490 } 8491 8492 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 8493 return SelCC; 8494 8495 return SDValue(); 8496 } 8497 8498 SDValue TargetLowering::expandFMINIMUM_FMAXIMUM(SDNode *N, 8499 SelectionDAG &DAG) const { 8500 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG)) 8501 return Expanded; 8502 8503 SDLoc DL(N); 8504 SDValue LHS = N->getOperand(0); 8505 SDValue RHS = N->getOperand(1); 8506 unsigned Opc = N->getOpcode(); 8507 EVT VT = N->getValueType(0); 8508 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8509 bool IsMax = Opc == ISD::FMAXIMUM; 8510 SDNodeFlags Flags = N->getFlags(); 8511 8512 // First, implement comparison not propagating NaN. If no native fmin or fmax 8513 // available, use plain select with setcc instead. 8514 SDValue MinMax; 8515 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 8516 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM; 8517 8518 // FIXME: We should probably define fminnum/fmaxnum variants with correct 8519 // signed zero behavior. 8520 bool MinMaxMustRespectOrderedZero = false; 8521 8522 if (isOperationLegalOrCustom(CompOpcIeee, VT)) { 8523 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags); 8524 MinMaxMustRespectOrderedZero = true; 8525 } else if (isOperationLegalOrCustom(CompOpc, VT)) { 8526 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags); 8527 } else { 8528 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8529 return DAG.UnrollVectorOp(N); 8530 8531 // NaN (if exists) will be propagated later, so orderness doesn't matter. 8532 SDValue Compare = 8533 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT); 8534 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags); 8535 } 8536 8537 // Propagate any NaN of both operands 8538 if (!N->getFlags().hasNoNaNs() && 8539 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) { 8540 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(), 8541 APFloat::getNaN(VT.getFltSemantics())); 8542 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO), 8543 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags); 8544 } 8545 8546 // fminimum/fmaximum requires -0.0 less than +0.0 8547 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() && 8548 !DAG.isKnownNeverZeroFloat(RHS) && !DAG.isKnownNeverZeroFloat(LHS)) { 8549 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax, 8550 DAG.getConstantFP(0.0, DL, VT), ISD::SETOEQ); 8551 SDValue TestZero = 8552 DAG.getTargetConstant(IsMax ? fcPosZero : fcNegZero, DL, MVT::i32); 8553 SDValue LCmp = DAG.getSelect( 8554 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, LHS, TestZero), LHS, 8555 MinMax, Flags); 8556 SDValue RCmp = DAG.getSelect( 8557 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, RHS, TestZero), RHS, 8558 LCmp, Flags); 8559 MinMax = DAG.getSelect(DL, VT, IsZero, RCmp, MinMax, Flags); 8560 } 8561 8562 return MinMax; 8563 } 8564 8565 SDValue TargetLowering::expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *Node, 8566 SelectionDAG &DAG) const { 8567 SDLoc DL(Node); 8568 SDValue LHS = Node->getOperand(0); 8569 SDValue RHS = Node->getOperand(1); 8570 unsigned Opc = Node->getOpcode(); 8571 EVT VT = Node->getValueType(0); 8572 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8573 bool IsMax = Opc == ISD::FMAXIMUMNUM; 8574 const TargetOptions &Options = DAG.getTarget().Options; 8575 SDNodeFlags Flags = Node->getFlags(); 8576 8577 unsigned NewOp = 8578 Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 8579 8580 if (isOperationLegalOrCustom(NewOp, VT)) { 8581 if (!Flags.hasNoNaNs()) { 8582 // Insert canonicalizes if it's possible we need to quiet to get correct 8583 // sNaN behavior. 8584 if (!DAG.isKnownNeverSNaN(LHS)) { 8585 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags); 8586 } 8587 if (!DAG.isKnownNeverSNaN(RHS)) { 8588 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags); 8589 } 8590 } 8591 8592 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags); 8593 } 8594 8595 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has 8596 // same behaviors for all of other cases: +0.0 vs -0.0 included. 8597 if (Flags.hasNoNaNs() || 8598 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) { 8599 unsigned IEEE2019Op = 8600 Opc == ISD::FMINIMUMNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 8601 if (isOperationLegalOrCustom(IEEE2019Op, VT)) 8602 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags); 8603 } 8604 8605 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return 8606 // either one for +0.0 vs -0.0. 8607 if ((Flags.hasNoNaNs() || 8608 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) && 8609 (Flags.hasNoSignedZeros() || DAG.isKnownNeverZeroFloat(LHS) || 8610 DAG.isKnownNeverZeroFloat(RHS))) { 8611 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM; 8612 if (isOperationLegalOrCustom(IEEE2008Op, VT)) 8613 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags); 8614 } 8615 8616 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8617 return DAG.UnrollVectorOp(Node); 8618 8619 // If only one operand is NaN, override it with another operand. 8620 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) { 8621 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO); 8622 } 8623 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) { 8624 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO); 8625 } 8626 8627 SDValue MinMax = 8628 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT); 8629 // If MinMax is NaN, let's quiet it. 8630 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS) && 8631 !DAG.isKnownNeverNaN(RHS)) { 8632 MinMax = DAG.getNode(ISD::FCANONICALIZE, DL, VT, MinMax, Flags); 8633 } 8634 8635 // Fixup signed zero behavior. 8636 if (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros() || 8637 DAG.isKnownNeverZeroFloat(LHS) || DAG.isKnownNeverZeroFloat(RHS)) { 8638 return MinMax; 8639 } 8640 SDValue TestZero = 8641 DAG.getTargetConstant(IsMax ? fcPosZero : fcNegZero, DL, MVT::i32); 8642 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax, 8643 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ); 8644 SDValue LCmp = DAG.getSelect( 8645 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, LHS, TestZero), LHS, 8646 MinMax, Flags); 8647 SDValue RCmp = DAG.getSelect( 8648 DL, VT, DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, RHS, TestZero), RHS, LCmp, 8649 Flags); 8650 return DAG.getSelect(DL, VT, IsZero, RCmp, MinMax, Flags); 8651 } 8652 8653 /// Returns a true value if if this FPClassTest can be performed with an ordered 8654 /// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns 8655 /// std::nullopt if it cannot be performed as a compare with 0. 8656 static std::optional<bool> isFCmpEqualZero(FPClassTest Test, 8657 const fltSemantics &Semantics, 8658 const MachineFunction &MF) { 8659 FPClassTest OrderedMask = Test & ~fcNan; 8660 FPClassTest NanTest = Test & fcNan; 8661 bool IsOrdered = NanTest == fcNone; 8662 bool IsUnordered = NanTest == fcNan; 8663 8664 // Skip cases that are testing for only a qnan or snan. 8665 if (!IsOrdered && !IsUnordered) 8666 return std::nullopt; 8667 8668 if (OrderedMask == fcZero && 8669 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE) 8670 return IsOrdered; 8671 if (OrderedMask == (fcZero | fcSubnormal) && 8672 MF.getDenormalMode(Semantics).inputsAreZero()) 8673 return IsOrdered; 8674 return std::nullopt; 8675 } 8676 8677 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 8678 const FPClassTest OrigTestMask, 8679 SDNodeFlags Flags, const SDLoc &DL, 8680 SelectionDAG &DAG) const { 8681 EVT OperandVT = Op.getValueType(); 8682 assert(OperandVT.isFloatingPoint()); 8683 FPClassTest Test = OrigTestMask; 8684 8685 // Degenerated cases. 8686 if (Test == fcNone) 8687 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 8688 if (Test == fcAllFlags) 8689 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 8690 8691 // PPC double double is a pair of doubles, of which the higher part determines 8692 // the value class. 8693 if (OperandVT == MVT::ppcf128) { 8694 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 8695 DAG.getConstant(1, DL, MVT::i32)); 8696 OperandVT = MVT::f64; 8697 } 8698 8699 // Floating-point type properties. 8700 EVT ScalarFloatVT = OperandVT.getScalarType(); 8701 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 8702 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 8703 bool IsF80 = (ScalarFloatVT == MVT::f80); 8704 8705 // Some checks can be implemented using float comparisons, if floating point 8706 // exceptions are ignored. 8707 if (Flags.hasNoFPExcept() && 8708 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 8709 FPClassTest FPTestMask = Test; 8710 bool IsInvertedFP = false; 8711 8712 if (FPClassTest InvertedFPCheck = 8713 invertFPClassTestIfSimpler(FPTestMask, true)) { 8714 FPTestMask = InvertedFPCheck; 8715 IsInvertedFP = true; 8716 } 8717 8718 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ; 8719 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ; 8720 8721 // See if we can fold an | fcNan into an unordered compare. 8722 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan; 8723 8724 // Can't fold the ordered check if we're only testing for snan or qnan 8725 // individually. 8726 if ((FPTestMask & fcNan) != fcNan) 8727 OrderedFPTestMask = FPTestMask; 8728 8729 const bool IsOrdered = FPTestMask == OrderedFPTestMask; 8730 8731 if (std::optional<bool> IsCmp0 = 8732 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction()); 8733 IsCmp0 && (isCondCodeLegalOrCustom( 8734 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode, 8735 OperandVT.getScalarType().getSimpleVT()))) { 8736 8737 // If denormals could be implicitly treated as 0, this is not equivalent 8738 // to a compare with 0 since it will also be true for denormals. 8739 return DAG.getSetCC(DL, ResultVT, Op, 8740 DAG.getConstantFP(0.0, DL, OperandVT), 8741 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode); 8742 } 8743 8744 if (FPTestMask == fcNan && 8745 isCondCodeLegalOrCustom(IsInvertedFP ? ISD::SETO : ISD::SETUO, 8746 OperandVT.getScalarType().getSimpleVT())) 8747 return DAG.getSetCC(DL, ResultVT, Op, Op, 8748 IsInvertedFP ? ISD::SETO : ISD::SETUO); 8749 8750 bool IsOrderedInf = FPTestMask == fcInf; 8751 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) && 8752 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode 8753 : UnorderedCmpOpcode, 8754 OperandVT.getScalarType().getSimpleVT()) && 8755 isOperationLegalOrCustom(ISD::FABS, OperandVT.getScalarType()) && 8756 (isOperationLegal(ISD::ConstantFP, OperandVT.getScalarType()) || 8757 (OperandVT.isVector() && 8758 isOperationLegalOrCustom(ISD::BUILD_VECTOR, OperandVT)))) { 8759 // isinf(x) --> fabs(x) == inf 8760 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8761 SDValue Inf = 8762 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT); 8763 return DAG.getSetCC(DL, ResultVT, Abs, Inf, 8764 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode); 8765 } 8766 8767 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) && 8768 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode 8769 : UnorderedCmpOpcode, 8770 OperandVT.getSimpleVT())) { 8771 // isposinf(x) --> x == inf 8772 // isneginf(x) --> x == -inf 8773 // isposinf(x) || nan --> x u== inf 8774 // isneginf(x) || nan --> x u== -inf 8775 8776 SDValue Inf = DAG.getConstantFP( 8777 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL, 8778 OperandVT); 8779 return DAG.getSetCC(DL, ResultVT, Op, Inf, 8780 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode); 8781 } 8782 8783 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) { 8784 // TODO: Could handle ordered case, but it produces worse code for 8785 // x86. Maybe handle ordered if fabs is free? 8786 8787 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT; 8788 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT; 8789 8790 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp, 8791 OperandVT.getScalarType().getSimpleVT())) { 8792 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal 8793 8794 // TODO: Maybe only makes sense if fabs is free. Integer test of 8795 // exponent bits seems better for x86. 8796 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8797 SDValue SmallestNormal = DAG.getConstantFP( 8798 APFloat::getSmallestNormalized(Semantics), DL, OperandVT); 8799 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, 8800 IsOrdered ? OrderedOp : UnorderedOp); 8801 } 8802 } 8803 8804 if (FPTestMask == fcNormal) { 8805 // TODO: Handle unordered 8806 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT; 8807 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE; 8808 8809 if (isCondCodeLegalOrCustom(IsFiniteOp, 8810 OperandVT.getScalarType().getSimpleVT()) && 8811 isCondCodeLegalOrCustom(IsNormalOp, 8812 OperandVT.getScalarType().getSimpleVT()) && 8813 isFAbsFree(OperandVT)) { 8814 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal) 8815 SDValue Inf = 8816 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT); 8817 SDValue SmallestNormal = DAG.getConstantFP( 8818 APFloat::getSmallestNormalized(Semantics), DL, OperandVT); 8819 8820 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8821 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp); 8822 SDValue IsNormal = 8823 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp); 8824 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND; 8825 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal); 8826 } 8827 } 8828 } 8829 8830 // Some checks may be represented as inversion of simpler check, for example 8831 // "inf|normal|subnormal|zero" => !"nan". 8832 bool IsInverted = false; 8833 8834 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) { 8835 Test = InvertedCheck; 8836 IsInverted = true; 8837 } 8838 8839 // In the general case use integer operations. 8840 unsigned BitSize = OperandVT.getScalarSizeInBits(); 8841 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 8842 if (OperandVT.isVector()) 8843 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 8844 OperandVT.getVectorElementCount()); 8845 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 8846 8847 // Various masks. 8848 APInt SignBit = APInt::getSignMask(BitSize); 8849 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 8850 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 8851 const unsigned ExplicitIntBitInF80 = 63; 8852 APInt ExpMask = Inf; 8853 if (IsF80) 8854 ExpMask.clearBit(ExplicitIntBitInF80); 8855 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 8856 APInt QNaNBitMask = 8857 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 8858 APInt InvertionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits()); 8859 8860 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 8861 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 8862 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 8863 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 8864 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 8865 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 8866 8867 SDValue Res; 8868 const auto appendResult = [&](SDValue PartialRes) { 8869 if (PartialRes) { 8870 if (Res) 8871 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 8872 else 8873 Res = PartialRes; 8874 } 8875 }; 8876 8877 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 8878 const auto getIntBitIsSet = [&]() -> SDValue { 8879 if (!IntBitIsSetV) { 8880 APInt IntBitMask(BitSize, 0); 8881 IntBitMask.setBit(ExplicitIntBitInF80); 8882 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 8883 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 8884 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 8885 } 8886 return IntBitIsSetV; 8887 }; 8888 8889 // Split the value into sign bit and absolute value. 8890 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 8891 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 8892 DAG.getConstant(0, DL, IntVT), ISD::SETLT); 8893 8894 // Tests that involve more than one class should be processed first. 8895 SDValue PartialRes; 8896 8897 if (IsF80) 8898 ; // Detect finite numbers of f80 by checking individual classes because 8899 // they have different settings of the explicit integer bit. 8900 else if ((Test & fcFinite) == fcFinite) { 8901 // finite(V) ==> abs(V) < exp_mask 8902 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8903 Test &= ~fcFinite; 8904 } else if ((Test & fcFinite) == fcPosFinite) { 8905 // finite(V) && V > 0 ==> V < exp_mask 8906 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 8907 Test &= ~fcPosFinite; 8908 } else if ((Test & fcFinite) == fcNegFinite) { 8909 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 8910 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8911 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8912 Test &= ~fcNegFinite; 8913 } 8914 appendResult(PartialRes); 8915 8916 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) { 8917 // fcZero | fcSubnormal => test all exponent bits are 0 8918 // TODO: Handle sign bit specific cases 8919 if (PartialCheck == (fcZero | fcSubnormal)) { 8920 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV); 8921 SDValue ExpIsZero = 8922 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 8923 appendResult(ExpIsZero); 8924 Test &= ~PartialCheck & fcAllFlags; 8925 } 8926 } 8927 8928 // Check for individual classes. 8929 8930 if (unsigned PartialCheck = Test & fcZero) { 8931 if (PartialCheck == fcPosZero) 8932 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 8933 else if (PartialCheck == fcZero) 8934 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 8935 else // ISD::fcNegZero 8936 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 8937 appendResult(PartialRes); 8938 } 8939 8940 if (unsigned PartialCheck = Test & fcSubnormal) { 8941 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 8942 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 8943 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 8944 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 8945 SDValue VMinusOneV = 8946 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 8947 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 8948 if (PartialCheck == fcNegSubnormal) 8949 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8950 appendResult(PartialRes); 8951 } 8952 8953 if (unsigned PartialCheck = Test & fcInf) { 8954 if (PartialCheck == fcPosInf) 8955 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 8956 else if (PartialCheck == fcInf) 8957 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 8958 else { // ISD::fcNegInf 8959 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 8960 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 8961 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 8962 } 8963 appendResult(PartialRes); 8964 } 8965 8966 if (unsigned PartialCheck = Test & fcNan) { 8967 APInt InfWithQnanBit = Inf | QNaNBitMask; 8968 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 8969 if (PartialCheck == fcNan) { 8970 // isnan(V) ==> abs(V) > int(inf) 8971 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 8972 if (IsF80) { 8973 // Recognize unsupported values as NaNs for compatibility with glibc. 8974 // In them (exp(V)==0) == int_bit. 8975 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 8976 SDValue ExpIsZero = 8977 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 8978 SDValue IsPseudo = 8979 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 8980 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 8981 } 8982 } else if (PartialCheck == fcQNan) { 8983 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 8984 PartialRes = 8985 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 8986 } else { // ISD::fcSNan 8987 // issignaling(V) ==> abs(V) > unsigned(Inf) && 8988 // abs(V) < (unsigned(Inf) | quiet_bit) 8989 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 8990 SDValue IsNotQnan = 8991 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 8992 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 8993 } 8994 appendResult(PartialRes); 8995 } 8996 8997 if (unsigned PartialCheck = Test & fcNormal) { 8998 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 8999 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 9000 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 9001 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 9002 APInt ExpLimit = ExpMask - ExpLSB; 9003 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 9004 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 9005 if (PartialCheck == fcNegNormal) 9006 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 9007 else if (PartialCheck == fcPosNormal) { 9008 SDValue PosSignV = 9009 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 9010 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 9011 } 9012 if (IsF80) 9013 PartialRes = 9014 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 9015 appendResult(PartialRes); 9016 } 9017 9018 if (!Res) 9019 return DAG.getConstant(IsInverted, DL, ResultVT); 9020 if (IsInverted) 9021 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 9022 return Res; 9023 } 9024 9025 // Only expand vector types if we have the appropriate vector bit operations. 9026 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 9027 assert(VT.isVector() && "Expected vector type"); 9028 unsigned Len = VT.getScalarSizeInBits(); 9029 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 9030 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 9031 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 9032 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 9033 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 9034 } 9035 9036 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 9037 SDLoc dl(Node); 9038 EVT VT = Node->getValueType(0); 9039 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9040 SDValue Op = Node->getOperand(0); 9041 unsigned Len = VT.getScalarSizeInBits(); 9042 assert(VT.isInteger() && "CTPOP not implemented for this type."); 9043 9044 // TODO: Add support for irregular type lengths. 9045 if (!(Len <= 128 && Len % 8 == 0)) 9046 return SDValue(); 9047 9048 // Only expand vector types if we have the appropriate vector bit operations. 9049 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 9050 return SDValue(); 9051 9052 // This is the "best" algorithm from 9053 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 9054 SDValue Mask55 = 9055 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 9056 SDValue Mask33 = 9057 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 9058 SDValue Mask0F = 9059 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 9060 9061 // v = v - ((v >> 1) & 0x55555555...) 9062 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 9063 DAG.getNode(ISD::AND, dl, VT, 9064 DAG.getNode(ISD::SRL, dl, VT, Op, 9065 DAG.getConstant(1, dl, ShVT)), 9066 Mask55)); 9067 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 9068 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 9069 DAG.getNode(ISD::AND, dl, VT, 9070 DAG.getNode(ISD::SRL, dl, VT, Op, 9071 DAG.getConstant(2, dl, ShVT)), 9072 Mask33)); 9073 // v = (v + (v >> 4)) & 0x0F0F0F0F... 9074 Op = DAG.getNode(ISD::AND, dl, VT, 9075 DAG.getNode(ISD::ADD, dl, VT, Op, 9076 DAG.getNode(ISD::SRL, dl, VT, Op, 9077 DAG.getConstant(4, dl, ShVT))), 9078 Mask0F); 9079 9080 if (Len <= 8) 9081 return Op; 9082 9083 // Avoid the multiply if we only have 2 bytes to add. 9084 // TODO: Only doing this for scalars because vectors weren't as obviously 9085 // improved. 9086 if (Len == 16 && !VT.isVector()) { 9087 // v = (v + (v >> 8)) & 0x00FF; 9088 return DAG.getNode(ISD::AND, dl, VT, 9089 DAG.getNode(ISD::ADD, dl, VT, Op, 9090 DAG.getNode(ISD::SRL, dl, VT, Op, 9091 DAG.getConstant(8, dl, ShVT))), 9092 DAG.getConstant(0xFF, dl, VT)); 9093 } 9094 9095 // v = (v * 0x01010101...) >> (Len - 8) 9096 SDValue V; 9097 if (isOperationLegalOrCustomOrPromote( 9098 ISD::MUL, getTypeToTransformTo(*DAG.getContext(), VT))) { 9099 SDValue Mask01 = 9100 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 9101 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01); 9102 } else { 9103 V = Op; 9104 for (unsigned Shift = 8; Shift < Len; Shift *= 2) { 9105 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl); 9106 V = DAG.getNode(ISD::ADD, dl, VT, V, 9107 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC)); 9108 } 9109 } 9110 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT)); 9111 } 9112 9113 SDValue TargetLowering::expandVPCTPOP(SDNode *Node, SelectionDAG &DAG) const { 9114 SDLoc dl(Node); 9115 EVT VT = Node->getValueType(0); 9116 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9117 SDValue Op = Node->getOperand(0); 9118 SDValue Mask = Node->getOperand(1); 9119 SDValue VL = Node->getOperand(2); 9120 unsigned Len = VT.getScalarSizeInBits(); 9121 assert(VT.isInteger() && "VP_CTPOP not implemented for this type."); 9122 9123 // TODO: Add support for irregular type lengths. 9124 if (!(Len <= 128 && Len % 8 == 0)) 9125 return SDValue(); 9126 9127 // This is same algorithm of expandCTPOP from 9128 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 9129 SDValue Mask55 = 9130 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 9131 SDValue Mask33 = 9132 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 9133 SDValue Mask0F = 9134 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 9135 9136 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5; 9137 9138 // v = v - ((v >> 1) & 0x55555555...) 9139 Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT, 9140 DAG.getNode(ISD::VP_SRL, dl, VT, Op, 9141 DAG.getConstant(1, dl, ShVT), Mask, VL), 9142 Mask55, Mask, VL); 9143 Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL); 9144 9145 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 9146 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL); 9147 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, 9148 DAG.getNode(ISD::VP_SRL, dl, VT, Op, 9149 DAG.getConstant(2, dl, ShVT), Mask, VL), 9150 Mask33, Mask, VL); 9151 Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL); 9152 9153 // v = (v + (v >> 4)) & 0x0F0F0F0F... 9154 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(4, dl, ShVT), 9155 Mask, VL), 9156 Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL); 9157 Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL); 9158 9159 if (Len <= 8) 9160 return Op; 9161 9162 // v = (v * 0x01010101...) >> (Len - 8) 9163 SDValue V; 9164 if (isOperationLegalOrCustomOrPromote( 9165 ISD::VP_MUL, getTypeToTransformTo(*DAG.getContext(), VT))) { 9166 SDValue Mask01 = 9167 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 9168 V = DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL); 9169 } else { 9170 V = Op; 9171 for (unsigned Shift = 8; Shift < Len; Shift *= 2) { 9172 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl); 9173 V = DAG.getNode(ISD::VP_ADD, dl, VT, V, 9174 DAG.getNode(ISD::VP_SHL, dl, VT, V, ShiftC, Mask, VL), 9175 Mask, VL); 9176 } 9177 } 9178 return DAG.getNode(ISD::VP_SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT), 9179 Mask, VL); 9180 } 9181 9182 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 9183 SDLoc dl(Node); 9184 EVT VT = Node->getValueType(0); 9185 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9186 SDValue Op = Node->getOperand(0); 9187 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9188 9189 // If the non-ZERO_UNDEF version is supported we can use that instead. 9190 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 9191 isOperationLegalOrCustom(ISD::CTLZ, VT)) 9192 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 9193 9194 // If the ZERO_UNDEF version is supported use that and handle the zero case. 9195 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 9196 EVT SetCCVT = 9197 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9198 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 9199 SDValue Zero = DAG.getConstant(0, dl, VT); 9200 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 9201 return DAG.getSelect(dl, VT, SrcIsZero, 9202 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 9203 } 9204 9205 // Only expand vector types if we have the appropriate vector bit operations. 9206 // This includes the operations needed to expand CTPOP if it isn't supported. 9207 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 9208 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 9209 !canExpandVectorCTPOP(*this, VT)) || 9210 !isOperationLegalOrCustom(ISD::SRL, VT) || 9211 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 9212 return SDValue(); 9213 9214 // for now, we do this: 9215 // x = x | (x >> 1); 9216 // x = x | (x >> 2); 9217 // ... 9218 // x = x | (x >>16); 9219 // x = x | (x >>32); // for 64-bit input 9220 // return popcount(~x); 9221 // 9222 // Ref: "Hacker's Delight" by Henry Warren 9223 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 9224 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 9225 Op = DAG.getNode(ISD::OR, dl, VT, Op, 9226 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 9227 } 9228 Op = DAG.getNOT(dl, Op, VT); 9229 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 9230 } 9231 9232 SDValue TargetLowering::expandVPCTLZ(SDNode *Node, SelectionDAG &DAG) const { 9233 SDLoc dl(Node); 9234 EVT VT = Node->getValueType(0); 9235 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9236 SDValue Op = Node->getOperand(0); 9237 SDValue Mask = Node->getOperand(1); 9238 SDValue VL = Node->getOperand(2); 9239 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9240 9241 // do this: 9242 // x = x | (x >> 1); 9243 // x = x | (x >> 2); 9244 // ... 9245 // x = x | (x >>16); 9246 // x = x | (x >>32); // for 64-bit input 9247 // return popcount(~x); 9248 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 9249 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 9250 Op = DAG.getNode(ISD::VP_OR, dl, VT, Op, 9251 DAG.getNode(ISD::VP_SRL, dl, VT, Op, Tmp, Mask, VL), Mask, 9252 VL); 9253 } 9254 Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getAllOnesConstant(dl, VT), 9255 Mask, VL); 9256 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL); 9257 } 9258 9259 SDValue TargetLowering::CTTZTableLookup(SDNode *Node, SelectionDAG &DAG, 9260 const SDLoc &DL, EVT VT, SDValue Op, 9261 unsigned BitWidth) const { 9262 if (BitWidth != 32 && BitWidth != 64) 9263 return SDValue(); 9264 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U) 9265 : APInt(64, 0x0218A392CD3D5DBFULL); 9266 const DataLayout &TD = DAG.getDataLayout(); 9267 MachinePointerInfo PtrInfo = 9268 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()); 9269 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth); 9270 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 9271 SDValue Lookup = DAG.getNode( 9272 ISD::SRL, DL, VT, 9273 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg), 9274 DAG.getConstant(DeBruijn, DL, VT)), 9275 DAG.getConstant(ShiftAmt, DL, VT)); 9276 Lookup = DAG.getSExtOrTrunc(Lookup, DL, getPointerTy(TD)); 9277 9278 SmallVector<uint8_t> Table(BitWidth, 0); 9279 for (unsigned i = 0; i < BitWidth; i++) { 9280 APInt Shl = DeBruijn.shl(i); 9281 APInt Lshr = Shl.lshr(ShiftAmt); 9282 Table[Lshr.getZExtValue()] = i; 9283 } 9284 9285 // Create a ConstantArray in Constant Pool 9286 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table); 9287 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD), 9288 TD.getPrefTypeAlign(CA->getType())); 9289 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(), 9290 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL), 9291 PtrInfo, MVT::i8); 9292 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF) 9293 return ExtLoad; 9294 9295 EVT SetCCVT = 9296 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9297 SDValue Zero = DAG.getConstant(0, DL, VT); 9298 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ); 9299 return DAG.getSelect(DL, VT, SrcIsZero, 9300 DAG.getConstant(BitWidth, DL, VT), ExtLoad); 9301 } 9302 9303 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 9304 SDLoc dl(Node); 9305 EVT VT = Node->getValueType(0); 9306 SDValue Op = Node->getOperand(0); 9307 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 9308 9309 // If the non-ZERO_UNDEF version is supported we can use that instead. 9310 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 9311 isOperationLegalOrCustom(ISD::CTTZ, VT)) 9312 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 9313 9314 // If the ZERO_UNDEF version is supported use that and handle the zero case. 9315 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 9316 EVT SetCCVT = 9317 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9318 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 9319 SDValue Zero = DAG.getConstant(0, dl, VT); 9320 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 9321 return DAG.getSelect(dl, VT, SrcIsZero, 9322 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 9323 } 9324 9325 // Only expand vector types if we have the appropriate vector bit operations. 9326 // This includes the operations needed to expand CTPOP if it isn't supported. 9327 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 9328 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 9329 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 9330 !canExpandVectorCTPOP(*this, VT)) || 9331 !isOperationLegalOrCustom(ISD::SUB, VT) || 9332 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 9333 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 9334 return SDValue(); 9335 9336 // Emit Table Lookup if ISD::CTLZ and ISD::CTPOP are not legal. 9337 if (!VT.isVector() && isOperationExpand(ISD::CTPOP, VT) && 9338 !isOperationLegal(ISD::CTLZ, VT)) 9339 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt)) 9340 return V; 9341 9342 // for now, we use: { return popcount(~x & (x - 1)); } 9343 // unless the target has ctlz but not ctpop, in which case we use: 9344 // { return 32 - nlz(~x & (x-1)); } 9345 // Ref: "Hacker's Delight" by Henry Warren 9346 SDValue Tmp = DAG.getNode( 9347 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 9348 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 9349 9350 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 9351 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 9352 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 9353 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 9354 } 9355 9356 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 9357 } 9358 9359 SDValue TargetLowering::expandVPCTTZ(SDNode *Node, SelectionDAG &DAG) const { 9360 SDValue Op = Node->getOperand(0); 9361 SDValue Mask = Node->getOperand(1); 9362 SDValue VL = Node->getOperand(2); 9363 SDLoc dl(Node); 9364 EVT VT = Node->getValueType(0); 9365 9366 // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1)) 9367 SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op, 9368 DAG.getAllOnesConstant(dl, VT), Mask, VL); 9369 SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op, 9370 DAG.getConstant(1, dl, VT), Mask, VL); 9371 SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL); 9372 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL); 9373 } 9374 9375 SDValue TargetLowering::expandVPCTTZElements(SDNode *N, 9376 SelectionDAG &DAG) const { 9377 // %cond = to_bool_vec %source 9378 // %splat = splat /*val=*/VL 9379 // %tz = step_vector 9380 // %v = vp.select %cond, /*true=*/tz, /*false=*/%splat 9381 // %r = vp.reduce.umin %v 9382 SDLoc DL(N); 9383 SDValue Source = N->getOperand(0); 9384 SDValue Mask = N->getOperand(1); 9385 SDValue EVL = N->getOperand(2); 9386 EVT SrcVT = Source.getValueType(); 9387 EVT ResVT = N->getValueType(0); 9388 EVT ResVecVT = 9389 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount()); 9390 9391 // Convert to boolean vector. 9392 if (SrcVT.getScalarType() != MVT::i1) { 9393 SDValue AllZero = DAG.getConstant(0, DL, SrcVT); 9394 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 9395 SrcVT.getVectorElementCount()); 9396 Source = DAG.getNode(ISD::VP_SETCC, DL, SrcVT, Source, AllZero, 9397 DAG.getCondCode(ISD::SETNE), Mask, EVL); 9398 } 9399 9400 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT); 9401 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL); 9402 SDValue StepVec = DAG.getStepVector(DL, ResVecVT); 9403 SDValue Select = 9404 DAG.getNode(ISD::VP_SELECT, DL, ResVecVT, Source, StepVec, Splat, EVL); 9405 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL); 9406 } 9407 9408 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 9409 bool IsNegative) const { 9410 SDLoc dl(N); 9411 EVT VT = N->getValueType(0); 9412 SDValue Op = N->getOperand(0); 9413 9414 // abs(x) -> smax(x,sub(0,x)) 9415 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 9416 isOperationLegal(ISD::SMAX, VT)) { 9417 SDValue Zero = DAG.getConstant(0, dl, VT); 9418 Op = DAG.getFreeze(Op); 9419 return DAG.getNode(ISD::SMAX, dl, VT, Op, 9420 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9421 } 9422 9423 // abs(x) -> umin(x,sub(0,x)) 9424 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 9425 isOperationLegal(ISD::UMIN, VT)) { 9426 SDValue Zero = DAG.getConstant(0, dl, VT); 9427 Op = DAG.getFreeze(Op); 9428 return DAG.getNode(ISD::UMIN, dl, VT, Op, 9429 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9430 } 9431 9432 // 0 - abs(x) -> smin(x, sub(0,x)) 9433 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 9434 isOperationLegal(ISD::SMIN, VT)) { 9435 SDValue Zero = DAG.getConstant(0, dl, VT); 9436 Op = DAG.getFreeze(Op); 9437 return DAG.getNode(ISD::SMIN, dl, VT, Op, 9438 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 9439 } 9440 9441 // Only expand vector types if we have the appropriate vector operations. 9442 if (VT.isVector() && 9443 (!isOperationLegalOrCustom(ISD::SRA, VT) || 9444 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 9445 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 9446 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 9447 return SDValue(); 9448 9449 Op = DAG.getFreeze(Op); 9450 SDValue Shift = DAG.getNode( 9451 ISD::SRA, dl, VT, Op, 9452 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl)); 9453 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 9454 9455 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 9456 if (!IsNegative) 9457 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 9458 9459 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 9460 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 9461 } 9462 9463 SDValue TargetLowering::expandABD(SDNode *N, SelectionDAG &DAG) const { 9464 SDLoc dl(N); 9465 EVT VT = N->getValueType(0); 9466 SDValue LHS = DAG.getFreeze(N->getOperand(0)); 9467 SDValue RHS = DAG.getFreeze(N->getOperand(1)); 9468 bool IsSigned = N->getOpcode() == ISD::ABDS; 9469 9470 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs)) 9471 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs)) 9472 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX; 9473 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN; 9474 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) { 9475 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS); 9476 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS); 9477 return DAG.getNode(ISD::SUB, dl, VT, Max, Min); 9478 } 9479 9480 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs)) 9481 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) 9482 return DAG.getNode(ISD::OR, dl, VT, 9483 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS), 9484 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS)); 9485 9486 // If the subtract doesn't overflow then just use abs(sub()) 9487 // NOTE: don't use frozen operands for value tracking. 9488 bool IsNonNegative = DAG.SignBitIsZero(N->getOperand(1)) && 9489 DAG.SignBitIsZero(N->getOperand(0)); 9490 9491 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, N->getOperand(0), 9492 N->getOperand(1))) 9493 return DAG.getNode(ISD::ABS, dl, VT, 9494 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS)); 9495 9496 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, N->getOperand(1), 9497 N->getOperand(0))) 9498 return DAG.getNode(ISD::ABS, dl, VT, 9499 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS)); 9500 9501 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9502 ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT; 9503 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC); 9504 9505 // Branchless expansion iff cmp result is allbits: 9506 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs))) 9507 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs))) 9508 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 9509 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 9510 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp); 9511 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor); 9512 } 9513 9514 // Similar to the branchless expansion, use the (sign-extended) usubo overflow 9515 // flag if the (scalar) type is illegal as this is more likely to legalize 9516 // cleanly: 9517 // abdu(lhs, rhs) -> sub(xor(sub(lhs, rhs), uof(lhs, rhs)), uof(lhs, rhs)) 9518 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT)) { 9519 SDValue USubO = 9520 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS}); 9521 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1)); 9522 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp); 9523 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp); 9524 } 9525 9526 // FIXME: Should really try to split the vector in case it's legal on a 9527 // subvector. 9528 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 9529 return DAG.UnrollVectorOp(N); 9530 9531 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9532 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9533 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS), 9534 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS)); 9535 } 9536 9537 SDValue TargetLowering::expandAVG(SDNode *N, SelectionDAG &DAG) const { 9538 SDLoc dl(N); 9539 EVT VT = N->getValueType(0); 9540 SDValue LHS = N->getOperand(0); 9541 SDValue RHS = N->getOperand(1); 9542 9543 unsigned Opc = N->getOpcode(); 9544 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU; 9545 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS; 9546 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB; 9547 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR; 9548 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL; 9549 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9550 assert((Opc == ISD::AVGFLOORS || Opc == ISD::AVGCEILS || 9551 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) && 9552 "Unknown AVG node"); 9553 9554 // If the operands are already extended, we can add+shift. 9555 bool IsExt = 9556 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 && 9557 DAG.ComputeNumSignBits(RHS) >= 2) || 9558 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 && 9559 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1); 9560 if (IsExt) { 9561 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS); 9562 if (!IsFloor) 9563 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT)); 9564 return DAG.getNode(ShiftOpc, dl, VT, Sum, 9565 DAG.getShiftAmountConstant(1, VT, dl)); 9566 } 9567 9568 // For scalars, see if we can efficiently extend/truncate to use add+shift. 9569 if (VT.isScalarInteger()) { 9570 unsigned BW = VT.getScalarSizeInBits(); 9571 EVT ExtVT = VT.getIntegerVT(*DAG.getContext(), 2 * BW); 9572 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) { 9573 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS); 9574 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS); 9575 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS); 9576 if (!IsFloor) 9577 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg, 9578 DAG.getConstant(1, dl, ExtVT)); 9579 // Just use SRL as we will be truncating away the extended sign bits. 9580 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg, 9581 DAG.getShiftAmountConstant(1, ExtVT, dl)); 9582 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg); 9583 } 9584 } 9585 9586 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1)) 9587 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT)) { 9588 SDValue UAddWithOverflow = 9589 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS}); 9590 9591 SDValue Sum = UAddWithOverflow.getValue(0); 9592 SDValue Overflow = UAddWithOverflow.getValue(1); 9593 9594 // Right shift the sum by 1 9595 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum, 9596 DAG.getShiftAmountConstant(1, VT, dl)); 9597 9598 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow); 9599 SDValue OverflowShl = DAG.getNode( 9600 ISD::SHL, dl, VT, ZeroExtOverflow, 9601 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl)); 9602 9603 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl); 9604 } 9605 9606 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1)) 9607 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1)) 9608 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1)) 9609 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1)) 9610 LHS = DAG.getFreeze(LHS); 9611 RHS = DAG.getFreeze(RHS); 9612 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS); 9613 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 9614 SDValue Shift = 9615 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl)); 9616 return DAG.getNode(SumOpc, dl, VT, Sign, Shift); 9617 } 9618 9619 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 9620 SDLoc dl(N); 9621 EVT VT = N->getValueType(0); 9622 SDValue Op = N->getOperand(0); 9623 9624 if (!VT.isSimple()) 9625 return SDValue(); 9626 9627 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9628 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9629 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9630 default: 9631 return SDValue(); 9632 case MVT::i16: 9633 // Use a rotate by 8. This can be further expanded if necessary. 9634 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9635 case MVT::i32: 9636 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9637 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op, 9638 DAG.getConstant(0xFF00, dl, VT)); 9639 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT)); 9640 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9641 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 9642 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9643 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9644 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9645 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9646 case MVT::i64: 9647 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9648 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op, 9649 DAG.getConstant(255ULL<<8, dl, VT)); 9650 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT)); 9651 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op, 9652 DAG.getConstant(255ULL<<16, dl, VT)); 9653 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT)); 9654 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op, 9655 DAG.getConstant(255ULL<<24, dl, VT)); 9656 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT)); 9657 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9658 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 9659 DAG.getConstant(255ULL<<24, dl, VT)); 9660 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9661 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 9662 DAG.getConstant(255ULL<<16, dl, VT)); 9663 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 9664 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 9665 DAG.getConstant(255ULL<<8, dl, VT)); 9666 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9667 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 9668 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 9669 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9670 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9671 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 9672 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9673 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 9674 } 9675 } 9676 9677 SDValue TargetLowering::expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const { 9678 SDLoc dl(N); 9679 EVT VT = N->getValueType(0); 9680 SDValue Op = N->getOperand(0); 9681 SDValue Mask = N->getOperand(1); 9682 SDValue EVL = N->getOperand(2); 9683 9684 if (!VT.isSimple()) 9685 return SDValue(); 9686 9687 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9688 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9689 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9690 default: 9691 return SDValue(); 9692 case MVT::i16: 9693 Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9694 Mask, EVL); 9695 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9696 Mask, EVL); 9697 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL); 9698 case MVT::i32: 9699 Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9700 Mask, EVL); 9701 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT), 9702 Mask, EVL); 9703 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT), 9704 Mask, EVL); 9705 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9706 Mask, EVL); 9707 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9708 DAG.getConstant(0xFF00, dl, VT), Mask, EVL); 9709 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9710 Mask, EVL); 9711 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9712 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9713 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9714 case MVT::i64: 9715 Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9716 Mask, EVL); 9717 Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9718 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9719 Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT), 9720 Mask, EVL); 9721 Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9722 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9723 Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT), 9724 Mask, EVL); 9725 Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9726 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9727 Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT), 9728 Mask, EVL); 9729 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9730 Mask, EVL); 9731 Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4, 9732 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9733 Tmp3 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9734 Mask, EVL); 9735 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3, 9736 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9737 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT), 9738 Mask, EVL); 9739 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9740 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9741 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9742 Mask, EVL); 9743 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL); 9744 Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL); 9745 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9746 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9747 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL); 9748 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9749 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL); 9750 } 9751 } 9752 9753 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9754 SDLoc dl(N); 9755 EVT VT = N->getValueType(0); 9756 SDValue Op = N->getOperand(0); 9757 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9758 unsigned Sz = VT.getScalarSizeInBits(); 9759 9760 SDValue Tmp, Tmp2, Tmp3; 9761 9762 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9763 // and finally the i1 pairs. 9764 // TODO: We can easily support i4/i2 legal types if any target ever does. 9765 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9766 // Create the masks - repeating the pattern every byte. 9767 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9768 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9769 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9770 9771 // BSWAP if the type is wider than a single byte. 9772 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 9773 9774 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9775 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 9776 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 9777 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 9778 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 9779 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9780 9781 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9782 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 9783 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 9784 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 9785 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 9786 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9787 9788 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9789 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 9790 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 9791 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 9792 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 9793 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9794 return Tmp; 9795 } 9796 9797 Tmp = DAG.getConstant(0, dl, VT); 9798 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 9799 if (I < J) 9800 Tmp2 = 9801 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 9802 else 9803 Tmp2 = 9804 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 9805 9806 APInt Shift = APInt::getOneBitSet(Sz, J); 9807 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 9808 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 9809 } 9810 9811 return Tmp; 9812 } 9813 9814 SDValue TargetLowering::expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9815 assert(N->getOpcode() == ISD::VP_BITREVERSE); 9816 9817 SDLoc dl(N); 9818 EVT VT = N->getValueType(0); 9819 SDValue Op = N->getOperand(0); 9820 SDValue Mask = N->getOperand(1); 9821 SDValue EVL = N->getOperand(2); 9822 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9823 unsigned Sz = VT.getScalarSizeInBits(); 9824 9825 SDValue Tmp, Tmp2, Tmp3; 9826 9827 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9828 // and finally the i1 pairs. 9829 // TODO: We can easily support i4/i2 legal types if any target ever does. 9830 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9831 // Create the masks - repeating the pattern every byte. 9832 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9833 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9834 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9835 9836 // BSWAP if the type is wider than a single byte. 9837 Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op); 9838 9839 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9840 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT), 9841 Mask, EVL); 9842 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9843 DAG.getConstant(Mask4, dl, VT), Mask, EVL); 9844 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT), 9845 Mask, EVL); 9846 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT), 9847 Mask, EVL); 9848 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9849 9850 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9851 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT), 9852 Mask, EVL); 9853 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9854 DAG.getConstant(Mask2, dl, VT), Mask, EVL); 9855 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT), 9856 Mask, EVL); 9857 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT), 9858 Mask, EVL); 9859 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9860 9861 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9862 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT), 9863 Mask, EVL); 9864 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9865 DAG.getConstant(Mask1, dl, VT), Mask, EVL); 9866 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT), 9867 Mask, EVL); 9868 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT), 9869 Mask, EVL); 9870 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9871 return Tmp; 9872 } 9873 return SDValue(); 9874 } 9875 9876 std::pair<SDValue, SDValue> 9877 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 9878 SelectionDAG &DAG) const { 9879 SDLoc SL(LD); 9880 SDValue Chain = LD->getChain(); 9881 SDValue BasePTR = LD->getBasePtr(); 9882 EVT SrcVT = LD->getMemoryVT(); 9883 EVT DstVT = LD->getValueType(0); 9884 ISD::LoadExtType ExtType = LD->getExtensionType(); 9885 9886 if (SrcVT.isScalableVector()) 9887 report_fatal_error("Cannot scalarize scalable vector loads"); 9888 9889 unsigned NumElem = SrcVT.getVectorNumElements(); 9890 9891 EVT SrcEltVT = SrcVT.getScalarType(); 9892 EVT DstEltVT = DstVT.getScalarType(); 9893 9894 // A vector must always be stored in memory as-is, i.e. without any padding 9895 // between the elements, since various code depend on it, e.g. in the 9896 // handling of a bitcast of a vector type to int, which may be done with a 9897 // vector store followed by an integer load. A vector that does not have 9898 // elements that are byte-sized must therefore be stored as an integer 9899 // built out of the extracted vector elements. 9900 if (!SrcEltVT.isByteSized()) { 9901 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 9902 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 9903 9904 unsigned NumSrcBits = SrcVT.getSizeInBits(); 9905 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 9906 9907 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 9908 SDValue SrcEltBitMask = DAG.getConstant( 9909 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 9910 9911 // Load the whole vector and avoid masking off the top bits as it makes 9912 // the codegen worse. 9913 SDValue Load = 9914 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 9915 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 9916 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9917 9918 SmallVector<SDValue, 8> Vals; 9919 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9920 unsigned ShiftIntoIdx = 9921 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 9922 SDValue ShiftAmount = DAG.getShiftAmountConstant( 9923 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL); 9924 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 9925 SDValue Elt = 9926 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 9927 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 9928 9929 if (ExtType != ISD::NON_EXTLOAD) { 9930 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 9931 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 9932 } 9933 9934 Vals.push_back(Scalar); 9935 } 9936 9937 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9938 return std::make_pair(Value, Load.getValue(1)); 9939 } 9940 9941 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 9942 assert(SrcEltVT.isByteSized()); 9943 9944 SmallVector<SDValue, 8> Vals; 9945 SmallVector<SDValue, 8> LoadChains; 9946 9947 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9948 SDValue ScalarLoad = 9949 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 9950 LD->getPointerInfo().getWithOffset(Idx * Stride), 9951 SrcEltVT, LD->getOriginalAlign(), 9952 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9953 9954 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride)); 9955 9956 Vals.push_back(ScalarLoad.getValue(0)); 9957 LoadChains.push_back(ScalarLoad.getValue(1)); 9958 } 9959 9960 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 9961 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9962 9963 return std::make_pair(Value, NewChain); 9964 } 9965 9966 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 9967 SelectionDAG &DAG) const { 9968 SDLoc SL(ST); 9969 9970 SDValue Chain = ST->getChain(); 9971 SDValue BasePtr = ST->getBasePtr(); 9972 SDValue Value = ST->getValue(); 9973 EVT StVT = ST->getMemoryVT(); 9974 9975 if (StVT.isScalableVector()) 9976 report_fatal_error("Cannot scalarize scalable vector stores"); 9977 9978 // The type of the data we want to save 9979 EVT RegVT = Value.getValueType(); 9980 EVT RegSclVT = RegVT.getScalarType(); 9981 9982 // The type of data as saved in memory. 9983 EVT MemSclVT = StVT.getScalarType(); 9984 9985 unsigned NumElem = StVT.getVectorNumElements(); 9986 9987 // A vector must always be stored in memory as-is, i.e. without any padding 9988 // between the elements, since various code depend on it, e.g. in the 9989 // handling of a bitcast of a vector type to int, which may be done with a 9990 // vector store followed by an integer load. A vector that does not have 9991 // elements that are byte-sized must therefore be stored as an integer 9992 // built out of the extracted vector elements. 9993 if (!MemSclVT.isByteSized()) { 9994 unsigned NumBits = StVT.getSizeInBits(); 9995 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 9996 9997 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 9998 9999 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 10000 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 10001 DAG.getVectorIdxConstant(Idx, SL)); 10002 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 10003 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 10004 unsigned ShiftIntoIdx = 10005 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 10006 SDValue ShiftAmount = 10007 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 10008 SDValue ShiftedElt = 10009 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 10010 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 10011 } 10012 10013 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 10014 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 10015 ST->getAAInfo()); 10016 } 10017 10018 // Store Stride in bytes 10019 unsigned Stride = MemSclVT.getSizeInBits() / 8; 10020 assert(Stride && "Zero stride!"); 10021 // Extract each of the elements from the original vector and save them into 10022 // memory individually. 10023 SmallVector<SDValue, 8> Stores; 10024 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 10025 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 10026 DAG.getVectorIdxConstant(Idx, SL)); 10027 10028 SDValue Ptr = 10029 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride)); 10030 10031 // This scalar TruncStore may be illegal, but we legalize it later. 10032 SDValue Store = DAG.getTruncStore( 10033 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 10034 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 10035 ST->getAAInfo()); 10036 10037 Stores.push_back(Store); 10038 } 10039 10040 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 10041 } 10042 10043 std::pair<SDValue, SDValue> 10044 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 10045 assert(LD->getAddressingMode() == ISD::UNINDEXED && 10046 "unaligned indexed loads not implemented!"); 10047 SDValue Chain = LD->getChain(); 10048 SDValue Ptr = LD->getBasePtr(); 10049 EVT VT = LD->getValueType(0); 10050 EVT LoadedVT = LD->getMemoryVT(); 10051 SDLoc dl(LD); 10052 auto &MF = DAG.getMachineFunction(); 10053 10054 if (VT.isFloatingPoint() || VT.isVector()) { 10055 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 10056 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 10057 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 10058 LoadedVT.isVector()) { 10059 // Scalarize the load and let the individual components be handled. 10060 return scalarizeVectorLoad(LD, DAG); 10061 } 10062 10063 // Expand to a (misaligned) integer load of the same size, 10064 // then bitconvert to floating point or vector. 10065 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 10066 LD->getMemOperand()); 10067 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 10068 if (LoadedVT != VT) 10069 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 10070 ISD::ANY_EXTEND, dl, VT, Result); 10071 10072 return std::make_pair(Result, newLoad.getValue(1)); 10073 } 10074 10075 // Copy the value to a (aligned) stack slot using (unaligned) integer 10076 // loads and stores, then do a (aligned) load from the stack slot. 10077 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 10078 unsigned LoadedBytes = LoadedVT.getStoreSize(); 10079 unsigned RegBytes = RegVT.getSizeInBits() / 8; 10080 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 10081 10082 // Make sure the stack slot is also aligned for the register type. 10083 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 10084 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 10085 SmallVector<SDValue, 8> Stores; 10086 SDValue StackPtr = StackBase; 10087 unsigned Offset = 0; 10088 10089 EVT PtrVT = Ptr.getValueType(); 10090 EVT StackPtrVT = StackPtr.getValueType(); 10091 10092 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 10093 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 10094 10095 // Do all but one copies using the full register width. 10096 for (unsigned i = 1; i < NumRegs; i++) { 10097 // Load one integer register's worth from the original location. 10098 SDValue Load = DAG.getLoad( 10099 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 10100 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 10101 LD->getAAInfo()); 10102 // Follow the load with a store to the stack slot. Remember the store. 10103 Stores.push_back(DAG.getStore( 10104 Load.getValue(1), dl, Load, StackPtr, 10105 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 10106 // Increment the pointers. 10107 Offset += RegBytes; 10108 10109 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 10110 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 10111 } 10112 10113 // The last copy may be partial. Do an extending load. 10114 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 10115 8 * (LoadedBytes - Offset)); 10116 SDValue Load = 10117 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 10118 LD->getPointerInfo().getWithOffset(Offset), MemVT, 10119 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 10120 LD->getAAInfo()); 10121 // Follow the load with a store to the stack slot. Remember the store. 10122 // On big-endian machines this requires a truncating store to ensure 10123 // that the bits end up in the right place. 10124 Stores.push_back(DAG.getTruncStore( 10125 Load.getValue(1), dl, Load, StackPtr, 10126 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 10127 10128 // The order of the stores doesn't matter - say it with a TokenFactor. 10129 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10130 10131 // Finally, perform the original load only redirected to the stack slot. 10132 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 10133 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 10134 LoadedVT); 10135 10136 // Callers expect a MERGE_VALUES node. 10137 return std::make_pair(Load, TF); 10138 } 10139 10140 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 10141 "Unaligned load of unsupported type."); 10142 10143 // Compute the new VT that is half the size of the old one. This is an 10144 // integer MVT. 10145 unsigned NumBits = LoadedVT.getSizeInBits(); 10146 EVT NewLoadedVT; 10147 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 10148 NumBits >>= 1; 10149 10150 Align Alignment = LD->getOriginalAlign(); 10151 unsigned IncrementSize = NumBits / 8; 10152 ISD::LoadExtType HiExtType = LD->getExtensionType(); 10153 10154 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 10155 if (HiExtType == ISD::NON_EXTLOAD) 10156 HiExtType = ISD::ZEXTLOAD; 10157 10158 // Load the value in two parts 10159 SDValue Lo, Hi; 10160 if (DAG.getDataLayout().isLittleEndian()) { 10161 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 10162 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10163 LD->getAAInfo()); 10164 10165 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10166 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 10167 LD->getPointerInfo().getWithOffset(IncrementSize), 10168 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10169 LD->getAAInfo()); 10170 } else { 10171 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 10172 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10173 LD->getAAInfo()); 10174 10175 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10176 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 10177 LD->getPointerInfo().getWithOffset(IncrementSize), 10178 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 10179 LD->getAAInfo()); 10180 } 10181 10182 // aggregate the two parts 10183 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl); 10184 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 10185 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 10186 10187 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 10188 Hi.getValue(1)); 10189 10190 return std::make_pair(Result, TF); 10191 } 10192 10193 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 10194 SelectionDAG &DAG) const { 10195 assert(ST->getAddressingMode() == ISD::UNINDEXED && 10196 "unaligned indexed stores not implemented!"); 10197 SDValue Chain = ST->getChain(); 10198 SDValue Ptr = ST->getBasePtr(); 10199 SDValue Val = ST->getValue(); 10200 EVT VT = Val.getValueType(); 10201 Align Alignment = ST->getOriginalAlign(); 10202 auto &MF = DAG.getMachineFunction(); 10203 EVT StoreMemVT = ST->getMemoryVT(); 10204 10205 SDLoc dl(ST); 10206 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 10207 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10208 if (isTypeLegal(intVT)) { 10209 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 10210 StoreMemVT.isVector()) { 10211 // Scalarize the store and let the individual components be handled. 10212 SDValue Result = scalarizeVectorStore(ST, DAG); 10213 return Result; 10214 } 10215 // Expand to a bitconvert of the value to the integer type of the 10216 // same size, then a (misaligned) int store. 10217 // FIXME: Does not handle truncating floating point stores! 10218 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 10219 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 10220 Alignment, ST->getMemOperand()->getFlags()); 10221 return Result; 10222 } 10223 // Do a (aligned) store to a stack slot, then copy from the stack slot 10224 // to the final destination using (unaligned) integer loads and stores. 10225 MVT RegVT = getRegisterType( 10226 *DAG.getContext(), 10227 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 10228 EVT PtrVT = Ptr.getValueType(); 10229 unsigned StoredBytes = StoreMemVT.getStoreSize(); 10230 unsigned RegBytes = RegVT.getSizeInBits() / 8; 10231 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 10232 10233 // Make sure the stack slot is also aligned for the register type. 10234 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 10235 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 10236 10237 // Perform the original store, only redirected to the stack slot. 10238 SDValue Store = DAG.getTruncStore( 10239 Chain, dl, Val, StackPtr, 10240 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 10241 10242 EVT StackPtrVT = StackPtr.getValueType(); 10243 10244 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 10245 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 10246 SmallVector<SDValue, 8> Stores; 10247 unsigned Offset = 0; 10248 10249 // Do all but one copies using the full register width. 10250 for (unsigned i = 1; i < NumRegs; i++) { 10251 // Load one integer register's worth from the stack slot. 10252 SDValue Load = DAG.getLoad( 10253 RegVT, dl, Store, StackPtr, 10254 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 10255 // Store it to the final location. Remember the store. 10256 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 10257 ST->getPointerInfo().getWithOffset(Offset), 10258 ST->getOriginalAlign(), 10259 ST->getMemOperand()->getFlags())); 10260 // Increment the pointers. 10261 Offset += RegBytes; 10262 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 10263 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 10264 } 10265 10266 // The last store may be partial. Do a truncating store. On big-endian 10267 // machines this requires an extending load from the stack slot to ensure 10268 // that the bits are in the right place. 10269 EVT LoadMemVT = 10270 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 10271 10272 // Load from the stack slot. 10273 SDValue Load = DAG.getExtLoad( 10274 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 10275 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 10276 10277 Stores.push_back( 10278 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 10279 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 10280 ST->getOriginalAlign(), 10281 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 10282 // The order of the stores doesn't matter - say it with a TokenFactor. 10283 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10284 return Result; 10285 } 10286 10287 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 10288 "Unaligned store of unknown type."); 10289 // Get the half-size VT 10290 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 10291 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 10292 unsigned IncrementSize = NumBits / 8; 10293 10294 // Divide the stored value in two parts. 10295 SDValue ShiftAmount = 10296 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl); 10297 SDValue Lo = Val; 10298 // If Val is a constant, replace the upper bits with 0. The SRL will constant 10299 // fold and not use the upper bits. A smaller constant may be easier to 10300 // materialize. 10301 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque()) 10302 Lo = DAG.getNode( 10303 ISD::AND, dl, VT, Lo, 10304 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl, 10305 VT)); 10306 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 10307 10308 // Store the two parts 10309 SDValue Store1, Store2; 10310 Store1 = DAG.getTruncStore(Chain, dl, 10311 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 10312 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 10313 ST->getMemOperand()->getFlags()); 10314 10315 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 10316 Store2 = DAG.getTruncStore( 10317 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 10318 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 10319 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 10320 10321 SDValue Result = 10322 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 10323 return Result; 10324 } 10325 10326 SDValue 10327 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 10328 const SDLoc &DL, EVT DataVT, 10329 SelectionDAG &DAG, 10330 bool IsCompressedMemory) const { 10331 SDValue Increment; 10332 EVT AddrVT = Addr.getValueType(); 10333 EVT MaskVT = Mask.getValueType(); 10334 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 10335 "Incompatible types of Data and Mask"); 10336 if (IsCompressedMemory) { 10337 if (DataVT.isScalableVector()) 10338 report_fatal_error( 10339 "Cannot currently handle compressed memory with scalable vectors"); 10340 // Incrementing the pointer according to number of '1's in the mask. 10341 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 10342 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 10343 if (MaskIntVT.getSizeInBits() < 32) { 10344 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 10345 MaskIntVT = MVT::i32; 10346 } 10347 10348 // Count '1's with POPCNT. 10349 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 10350 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 10351 // Scale is an element size in bytes. 10352 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 10353 AddrVT); 10354 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 10355 } else if (DataVT.isScalableVector()) { 10356 Increment = DAG.getVScale(DL, AddrVT, 10357 APInt(AddrVT.getFixedSizeInBits(), 10358 DataVT.getStoreSize().getKnownMinValue())); 10359 } else 10360 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 10361 10362 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 10363 } 10364 10365 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 10366 EVT VecVT, const SDLoc &dl, 10367 ElementCount SubEC) { 10368 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 10369 "Cannot index a scalable vector within a fixed-width vector"); 10370 10371 unsigned NElts = VecVT.getVectorMinNumElements(); 10372 unsigned NumSubElts = SubEC.getKnownMinValue(); 10373 EVT IdxVT = Idx.getValueType(); 10374 10375 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 10376 // If this is a constant index and we know the value plus the number of the 10377 // elements in the subvector minus one is less than the minimum number of 10378 // elements then it's safe to return Idx. 10379 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 10380 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 10381 return Idx; 10382 SDValue VS = 10383 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 10384 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 10385 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 10386 DAG.getConstant(NumSubElts, dl, IdxVT)); 10387 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 10388 } 10389 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 10390 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 10391 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 10392 DAG.getConstant(Imm, dl, IdxVT)); 10393 } 10394 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 10395 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 10396 DAG.getConstant(MaxIndex, dl, IdxVT)); 10397 } 10398 10399 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 10400 SDValue VecPtr, EVT VecVT, 10401 SDValue Index) const { 10402 return getVectorSubVecPointer( 10403 DAG, VecPtr, VecVT, 10404 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 10405 Index); 10406 } 10407 10408 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 10409 SDValue VecPtr, EVT VecVT, 10410 EVT SubVecVT, 10411 SDValue Index) const { 10412 SDLoc dl(Index); 10413 // Make sure the index type is big enough to compute in. 10414 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 10415 10416 EVT EltVT = VecVT.getVectorElementType(); 10417 10418 // Calculate the element offset and add it to the pointer. 10419 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 10420 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 10421 "Converting bits to bytes lost precision"); 10422 assert(SubVecVT.getVectorElementType() == EltVT && 10423 "Sub-vector must be a vector with matching element type"); 10424 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 10425 SubVecVT.getVectorElementCount()); 10426 10427 EVT IdxVT = Index.getValueType(); 10428 if (SubVecVT.isScalableVector()) 10429 Index = 10430 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 10431 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 10432 10433 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 10434 DAG.getConstant(EltSize, dl, IdxVT)); 10435 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 10436 } 10437 10438 //===----------------------------------------------------------------------===// 10439 // Implementation of Emulated TLS Model 10440 //===----------------------------------------------------------------------===// 10441 10442 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 10443 SelectionDAG &DAG) const { 10444 // Access to address of TLS varialbe xyz is lowered to a function call: 10445 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 10446 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10447 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0); 10448 SDLoc dl(GA); 10449 10450 ArgListTy Args; 10451 ArgListEntry Entry; 10452 const GlobalValue *GV = 10453 cast<GlobalValue>(GA->getGlobal()->stripPointerCastsAndAliases()); 10454 SmallString<32> NameString("__emutls_v."); 10455 NameString += GV->getName(); 10456 StringRef EmuTlsVarName(NameString); 10457 const GlobalVariable *EmuTlsVar = 10458 GV->getParent()->getNamedGlobal(EmuTlsVarName); 10459 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 10460 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 10461 Entry.Ty = VoidPtrType; 10462 Args.push_back(Entry); 10463 10464 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 10465 10466 TargetLowering::CallLoweringInfo CLI(DAG); 10467 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 10468 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 10469 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 10470 10471 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 10472 // At last for X86 targets, maybe good for other targets too? 10473 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10474 MFI.setAdjustsStack(true); // Is this only for X86 target? 10475 MFI.setHasCalls(true); 10476 10477 assert((GA->getOffset() == 0) && 10478 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 10479 return CallResult.first; 10480 } 10481 10482 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 10483 SelectionDAG &DAG) const { 10484 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 10485 if (!isCtlzFast()) 10486 return SDValue(); 10487 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10488 SDLoc dl(Op); 10489 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) { 10490 EVT VT = Op.getOperand(0).getValueType(); 10491 SDValue Zext = Op.getOperand(0); 10492 if (VT.bitsLT(MVT::i32)) { 10493 VT = MVT::i32; 10494 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 10495 } 10496 unsigned Log2b = Log2_32(VT.getSizeInBits()); 10497 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 10498 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 10499 DAG.getConstant(Log2b, dl, MVT::i32)); 10500 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 10501 } 10502 return SDValue(); 10503 } 10504 10505 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 10506 SDValue Op0 = Node->getOperand(0); 10507 SDValue Op1 = Node->getOperand(1); 10508 EVT VT = Op0.getValueType(); 10509 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10510 unsigned Opcode = Node->getOpcode(); 10511 SDLoc DL(Node); 10512 10513 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits 10514 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT && 10515 getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10516 Op0 = DAG.getFreeze(Op0); 10517 SDValue Zero = DAG.getConstant(0, DL, VT); 10518 return DAG.getNode(ISD::SUB, DL, VT, Op0, 10519 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ)); 10520 } 10521 10522 // umin(x,y) -> sub(x,usubsat(x,y)) 10523 // TODO: Missing freeze(Op0)? 10524 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 10525 isOperationLegal(ISD::USUBSAT, VT)) { 10526 return DAG.getNode(ISD::SUB, DL, VT, Op0, 10527 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 10528 } 10529 10530 // umax(x,y) -> add(x,usubsat(y,x)) 10531 // TODO: Missing freeze(Op0)? 10532 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 10533 isOperationLegal(ISD::USUBSAT, VT)) { 10534 return DAG.getNode(ISD::ADD, DL, VT, Op0, 10535 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 10536 } 10537 10538 // FIXME: Should really try to split the vector in case it's legal on a 10539 // subvector. 10540 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10541 return DAG.UnrollVectorOp(Node); 10542 10543 // Attempt to find an existing SETCC node that we can reuse. 10544 // TODO: Do we need a generic doesSETCCNodeExist? 10545 // TODO: Missing freeze(Op0)/freeze(Op1)? 10546 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC, 10547 ISD::CondCode PrefCommuteCC, 10548 ISD::CondCode AltCommuteCC) { 10549 SDVTList BoolVTList = DAG.getVTList(BoolVT); 10550 for (ISD::CondCode CC : {PrefCC, AltCC}) { 10551 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 10552 {Op0, Op1, DAG.getCondCode(CC)})) { 10553 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 10554 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 10555 } 10556 } 10557 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) { 10558 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 10559 {Op0, Op1, DAG.getCondCode(CC)})) { 10560 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 10561 return DAG.getSelect(DL, VT, Cond, Op1, Op0); 10562 } 10563 } 10564 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC); 10565 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 10566 }; 10567 10568 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 10569 // -> Y = (A < B) ? B : A 10570 // -> Y = (A >= B) ? A : B 10571 // -> Y = (A <= B) ? B : A 10572 switch (Opcode) { 10573 case ISD::SMAX: 10574 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE); 10575 case ISD::SMIN: 10576 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE); 10577 case ISD::UMAX: 10578 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE); 10579 case ISD::UMIN: 10580 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE); 10581 } 10582 10583 llvm_unreachable("How did we get here?"); 10584 } 10585 10586 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 10587 unsigned Opcode = Node->getOpcode(); 10588 SDValue LHS = Node->getOperand(0); 10589 SDValue RHS = Node->getOperand(1); 10590 EVT VT = LHS.getValueType(); 10591 SDLoc dl(Node); 10592 10593 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10594 assert(VT.isInteger() && "Expected operands to be integers"); 10595 10596 // usub.sat(a, b) -> umax(a, b) - b 10597 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 10598 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 10599 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 10600 } 10601 10602 // uadd.sat(a, b) -> umin(a, ~b) + b 10603 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 10604 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 10605 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 10606 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 10607 } 10608 10609 unsigned OverflowOp; 10610 switch (Opcode) { 10611 case ISD::SADDSAT: 10612 OverflowOp = ISD::SADDO; 10613 break; 10614 case ISD::UADDSAT: 10615 OverflowOp = ISD::UADDO; 10616 break; 10617 case ISD::SSUBSAT: 10618 OverflowOp = ISD::SSUBO; 10619 break; 10620 case ISD::USUBSAT: 10621 OverflowOp = ISD::USUBO; 10622 break; 10623 default: 10624 llvm_unreachable("Expected method to receive signed or unsigned saturation " 10625 "addition or subtraction node."); 10626 } 10627 10628 // FIXME: Should really try to split the vector in case it's legal on a 10629 // subvector. 10630 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10631 return DAG.UnrollVectorOp(Node); 10632 10633 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 10634 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10635 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10636 SDValue SumDiff = Result.getValue(0); 10637 SDValue Overflow = Result.getValue(1); 10638 SDValue Zero = DAG.getConstant(0, dl, VT); 10639 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 10640 10641 if (Opcode == ISD::UADDSAT) { 10642 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10643 // (LHS + RHS) | OverflowMask 10644 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10645 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 10646 } 10647 // Overflow ? 0xffff.... : (LHS + RHS) 10648 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 10649 } 10650 10651 if (Opcode == ISD::USUBSAT) { 10652 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10653 // (LHS - RHS) & ~OverflowMask 10654 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10655 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 10656 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 10657 } 10658 // Overflow ? 0 : (LHS - RHS) 10659 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 10660 } 10661 10662 if (Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) { 10663 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10664 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 10665 10666 KnownBits KnownLHS = DAG.computeKnownBits(LHS); 10667 KnownBits KnownRHS = DAG.computeKnownBits(RHS); 10668 10669 // If either of the operand signs are known, then they are guaranteed to 10670 // only saturate in one direction. If non-negative they will saturate 10671 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN. 10672 // 10673 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the 10674 // sign of 'y' has to be flipped. 10675 10676 bool LHSIsNonNegative = KnownLHS.isNonNegative(); 10677 bool RHSIsNonNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() 10678 : KnownRHS.isNegative(); 10679 if (LHSIsNonNegative || RHSIsNonNegative) { 10680 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10681 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff); 10682 } 10683 10684 bool LHSIsNegative = KnownLHS.isNegative(); 10685 bool RHSIsNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNegative() 10686 : KnownRHS.isNonNegative(); 10687 if (LHSIsNegative || RHSIsNegative) { 10688 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10689 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff); 10690 } 10691 } 10692 10693 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 10694 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10695 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10696 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 10697 DAG.getConstant(BitWidth - 1, dl, VT)); 10698 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 10699 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 10700 } 10701 10702 SDValue TargetLowering::expandCMP(SDNode *Node, SelectionDAG &DAG) const { 10703 unsigned Opcode = Node->getOpcode(); 10704 SDValue LHS = Node->getOperand(0); 10705 SDValue RHS = Node->getOperand(1); 10706 EVT VT = LHS.getValueType(); 10707 EVT ResVT = Node->getValueType(0); 10708 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10709 SDLoc dl(Node); 10710 10711 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT); 10712 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT); 10713 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate); 10714 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate); 10715 10716 // We can't perform arithmetic on i1 values. Extending them would 10717 // probably result in worse codegen, so let's just use two selects instead. 10718 // Some targets are also just better off using selects rather than subtraction 10719 // because one of the conditions can be merged with one of the selects. 10720 // And finally, if we don't know the contents of high bits of a boolean value 10721 // we can't perform any arithmetic either. 10722 if (shouldExpandCmpUsingSelects(VT) || BoolVT.getScalarSizeInBits() == 1 || 10723 getBooleanContents(BoolVT) == UndefinedBooleanContent) { 10724 SDValue SelectZeroOrOne = 10725 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT), 10726 DAG.getConstant(0, dl, ResVT)); 10727 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT), 10728 SelectZeroOrOne); 10729 } 10730 10731 if (getBooleanContents(BoolVT) == ZeroOrNegativeOneBooleanContent) 10732 std::swap(IsGT, IsLT); 10733 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl, 10734 ResVT); 10735 } 10736 10737 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 10738 unsigned Opcode = Node->getOpcode(); 10739 bool IsSigned = Opcode == ISD::SSHLSAT; 10740 SDValue LHS = Node->getOperand(0); 10741 SDValue RHS = Node->getOperand(1); 10742 EVT VT = LHS.getValueType(); 10743 SDLoc dl(Node); 10744 10745 assert((Node->getOpcode() == ISD::SSHLSAT || 10746 Node->getOpcode() == ISD::USHLSAT) && 10747 "Expected a SHLSAT opcode"); 10748 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10749 assert(VT.isInteger() && "Expected operands to be integers"); 10750 10751 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10752 return DAG.UnrollVectorOp(Node); 10753 10754 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 10755 10756 unsigned BW = VT.getScalarSizeInBits(); 10757 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10758 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 10759 SDValue Orig = 10760 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 10761 10762 SDValue SatVal; 10763 if (IsSigned) { 10764 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 10765 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 10766 SDValue Cond = 10767 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT); 10768 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax); 10769 } else { 10770 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 10771 } 10772 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE); 10773 return DAG.getSelect(dl, VT, Cond, SatVal, Result); 10774 } 10775 10776 void TargetLowering::forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, 10777 bool Signed, EVT WideVT, 10778 const SDValue LL, const SDValue LH, 10779 const SDValue RL, const SDValue RH, 10780 SDValue &Lo, SDValue &Hi) const { 10781 // We can fall back to a libcall with an illegal type for the MUL if we 10782 // have a libcall big enough. 10783 // Also, we can fall back to a division in some cases, but that's a big 10784 // performance hit in the general case. 10785 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 10786 if (WideVT == MVT::i16) 10787 LC = RTLIB::MUL_I16; 10788 else if (WideVT == MVT::i32) 10789 LC = RTLIB::MUL_I32; 10790 else if (WideVT == MVT::i64) 10791 LC = RTLIB::MUL_I64; 10792 else if (WideVT == MVT::i128) 10793 LC = RTLIB::MUL_I128; 10794 10795 if (LC == RTLIB::UNKNOWN_LIBCALL || !getLibcallName(LC)) { 10796 // We'll expand the multiplication by brute force because we have no other 10797 // options. This is a trivially-generalized version of the code from 10798 // Hacker's Delight (itself derived from Knuth's Algorithm M from section 10799 // 4.3.1). 10800 EVT VT = LL.getValueType(); 10801 unsigned Bits = VT.getSizeInBits(); 10802 unsigned HalfBits = Bits >> 1; 10803 SDValue Mask = 10804 DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT); 10805 SDValue LLL = DAG.getNode(ISD::AND, dl, VT, LL, Mask); 10806 SDValue RLL = DAG.getNode(ISD::AND, dl, VT, RL, Mask); 10807 10808 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LLL, RLL); 10809 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask); 10810 10811 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl); 10812 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift); 10813 SDValue LLH = DAG.getNode(ISD::SRL, dl, VT, LL, Shift); 10814 SDValue RLH = DAG.getNode(ISD::SRL, dl, VT, RL, Shift); 10815 10816 SDValue U = DAG.getNode(ISD::ADD, dl, VT, 10817 DAG.getNode(ISD::MUL, dl, VT, LLH, RLL), TH); 10818 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask); 10819 SDValue UH = DAG.getNode(ISD::SRL, dl, VT, U, Shift); 10820 10821 SDValue V = DAG.getNode(ISD::ADD, dl, VT, 10822 DAG.getNode(ISD::MUL, dl, VT, LLL, RLH), UL); 10823 SDValue VH = DAG.getNode(ISD::SRL, dl, VT, V, Shift); 10824 10825 SDValue W = 10826 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LLH, RLH), 10827 DAG.getNode(ISD::ADD, dl, VT, UH, VH)); 10828 Lo = DAG.getNode(ISD::ADD, dl, VT, TL, 10829 DAG.getNode(ISD::SHL, dl, VT, V, Shift)); 10830 10831 Hi = DAG.getNode(ISD::ADD, dl, VT, W, 10832 DAG.getNode(ISD::ADD, dl, VT, 10833 DAG.getNode(ISD::MUL, dl, VT, RH, LL), 10834 DAG.getNode(ISD::MUL, dl, VT, RL, LH))); 10835 } else { 10836 // Attempt a libcall. 10837 SDValue Ret; 10838 TargetLowering::MakeLibCallOptions CallOptions; 10839 CallOptions.setSExt(Signed); 10840 CallOptions.setIsPostTypeLegalization(true); 10841 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 10842 // Halves of WideVT are packed into registers in different order 10843 // depending on platform endianness. This is usually handled by 10844 // the C calling convention, but we can't defer to it in 10845 // the legalizer. 10846 SDValue Args[] = {LL, LH, RL, RH}; 10847 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10848 } else { 10849 SDValue Args[] = {LH, LL, RH, RL}; 10850 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10851 } 10852 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 10853 "Ret value is a collection of constituent nodes holding result."); 10854 if (DAG.getDataLayout().isLittleEndian()) { 10855 // Same as above. 10856 Lo = Ret.getOperand(0); 10857 Hi = Ret.getOperand(1); 10858 } else { 10859 Lo = Ret.getOperand(1); 10860 Hi = Ret.getOperand(0); 10861 } 10862 } 10863 } 10864 10865 void TargetLowering::forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, 10866 bool Signed, const SDValue LHS, 10867 const SDValue RHS, SDValue &Lo, 10868 SDValue &Hi) const { 10869 EVT VT = LHS.getValueType(); 10870 assert(RHS.getValueType() == VT && "Mismatching operand types"); 10871 10872 SDValue HiLHS; 10873 SDValue HiRHS; 10874 if (Signed) { 10875 // The high part is obtained by SRA'ing all but one of the bits of low 10876 // part. 10877 unsigned LoSize = VT.getFixedSizeInBits(); 10878 HiLHS = DAG.getNode( 10879 ISD::SRA, dl, VT, LHS, 10880 DAG.getConstant(LoSize - 1, dl, getPointerTy(DAG.getDataLayout()))); 10881 HiRHS = DAG.getNode( 10882 ISD::SRA, dl, VT, RHS, 10883 DAG.getConstant(LoSize - 1, dl, getPointerTy(DAG.getDataLayout()))); 10884 } else { 10885 HiLHS = DAG.getConstant(0, dl, VT); 10886 HiRHS = DAG.getConstant(0, dl, VT); 10887 } 10888 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2); 10889 forceExpandWideMUL(DAG, dl, Signed, WideVT, LHS, HiLHS, RHS, HiRHS, Lo, Hi); 10890 } 10891 10892 SDValue 10893 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 10894 assert((Node->getOpcode() == ISD::SMULFIX || 10895 Node->getOpcode() == ISD::UMULFIX || 10896 Node->getOpcode() == ISD::SMULFIXSAT || 10897 Node->getOpcode() == ISD::UMULFIXSAT) && 10898 "Expected a fixed point multiplication opcode"); 10899 10900 SDLoc dl(Node); 10901 SDValue LHS = Node->getOperand(0); 10902 SDValue RHS = Node->getOperand(1); 10903 EVT VT = LHS.getValueType(); 10904 unsigned Scale = Node->getConstantOperandVal(2); 10905 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 10906 Node->getOpcode() == ISD::UMULFIXSAT); 10907 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 10908 Node->getOpcode() == ISD::SMULFIXSAT); 10909 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10910 unsigned VTSize = VT.getScalarSizeInBits(); 10911 10912 if (!Scale) { 10913 // [us]mul.fix(a, b, 0) -> mul(a, b) 10914 if (!Saturating) { 10915 if (isOperationLegalOrCustom(ISD::MUL, VT)) 10916 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10917 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 10918 SDValue Result = 10919 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10920 SDValue Product = Result.getValue(0); 10921 SDValue Overflow = Result.getValue(1); 10922 SDValue Zero = DAG.getConstant(0, dl, VT); 10923 10924 APInt MinVal = APInt::getSignedMinValue(VTSize); 10925 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 10926 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10927 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10928 // Xor the inputs, if resulting sign bit is 0 the product will be 10929 // positive, else negative. 10930 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 10931 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 10932 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 10933 return DAG.getSelect(dl, VT, Overflow, Result, Product); 10934 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 10935 SDValue Result = 10936 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10937 SDValue Product = Result.getValue(0); 10938 SDValue Overflow = Result.getValue(1); 10939 10940 APInt MaxVal = APInt::getMaxValue(VTSize); 10941 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10942 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 10943 } 10944 } 10945 10946 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 10947 "Expected scale to be less than the number of bits if signed or at " 10948 "most the number of bits if unsigned."); 10949 assert(LHS.getValueType() == RHS.getValueType() && 10950 "Expected both operands to be the same type"); 10951 10952 // Get the upper and lower bits of the result. 10953 SDValue Lo, Hi; 10954 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 10955 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 10956 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VTSize * 2); 10957 if (VT.isVector()) 10958 WideVT = 10959 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 10960 if (isOperationLegalOrCustom(LoHiOp, VT)) { 10961 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 10962 Lo = Result.getValue(0); 10963 Hi = Result.getValue(1); 10964 } else if (isOperationLegalOrCustom(HiOp, VT)) { 10965 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10966 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 10967 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) { 10968 // Try for a multiplication using a wider type. 10969 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10970 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS); 10971 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS); 10972 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt); 10973 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res); 10974 SDValue Shifted = 10975 DAG.getNode(ISD::SRA, dl, WideVT, Res, 10976 DAG.getShiftAmountConstant(VTSize, WideVT, dl)); 10977 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted); 10978 } else if (VT.isVector()) { 10979 return SDValue(); 10980 } else { 10981 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi); 10982 } 10983 10984 if (Scale == VTSize) 10985 // Result is just the top half since we'd be shifting by the width of the 10986 // operand. Overflow impossible so this works for both UMULFIX and 10987 // UMULFIXSAT. 10988 return Hi; 10989 10990 // The result will need to be shifted right by the scale since both operands 10991 // are scaled. The result is given to us in 2 halves, so we only want part of 10992 // both in the result. 10993 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 10994 DAG.getShiftAmountConstant(Scale, VT, dl)); 10995 if (!Saturating) 10996 return Result; 10997 10998 if (!Signed) { 10999 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 11000 // widened multiplication) aren't all zeroes. 11001 11002 // Saturate to max if ((Hi >> Scale) != 0), 11003 // which is the same as if (Hi > ((1 << Scale) - 1)) 11004 APInt MaxVal = APInt::getMaxValue(VTSize); 11005 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 11006 dl, VT); 11007 Result = DAG.getSelectCC(dl, Hi, LowMask, 11008 DAG.getConstant(MaxVal, dl, VT), Result, 11009 ISD::SETUGT); 11010 11011 return Result; 11012 } 11013 11014 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 11015 // widened multiplication) aren't all ones or all zeroes. 11016 11017 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 11018 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 11019 11020 if (Scale == 0) { 11021 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 11022 DAG.getShiftAmountConstant(VTSize - 1, VT, dl)); 11023 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 11024 // Saturated to SatMin if wide product is negative, and SatMax if wide 11025 // product is positive ... 11026 SDValue Zero = DAG.getConstant(0, dl, VT); 11027 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 11028 ISD::SETLT); 11029 // ... but only if we overflowed. 11030 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 11031 } 11032 11033 // We handled Scale==0 above so all the bits to examine is in Hi. 11034 11035 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 11036 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 11037 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 11038 dl, VT); 11039 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 11040 // Saturate to min if (Hi >> (Scale - 1)) < -1), 11041 // which is the same as if (HI < (-1 << (Scale - 1)) 11042 SDValue HighMask = 11043 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 11044 dl, VT); 11045 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 11046 return Result; 11047 } 11048 11049 SDValue 11050 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 11051 SDValue LHS, SDValue RHS, 11052 unsigned Scale, SelectionDAG &DAG) const { 11053 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 11054 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 11055 "Expected a fixed point division opcode"); 11056 11057 EVT VT = LHS.getValueType(); 11058 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 11059 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 11060 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 11061 11062 // If there is enough room in the type to upscale the LHS or downscale the 11063 // RHS before the division, we can perform it in this type without having to 11064 // resize. For signed operations, the LHS headroom is the number of 11065 // redundant sign bits, and for unsigned ones it is the number of zeroes. 11066 // The headroom for the RHS is the number of trailing zeroes. 11067 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 11068 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 11069 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 11070 11071 // For signed saturating operations, we need to be able to detect true integer 11072 // division overflow; that is, when you have MIN / -EPS. However, this 11073 // is undefined behavior and if we emit divisions that could take such 11074 // values it may cause undesired behavior (arithmetic exceptions on x86, for 11075 // example). 11076 // Avoid this by requiring an extra bit so that we never get this case. 11077 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 11078 // signed saturating division, we need to emit a whopping 32-bit division. 11079 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 11080 return SDValue(); 11081 11082 unsigned LHSShift = std::min(LHSLead, Scale); 11083 unsigned RHSShift = Scale - LHSShift; 11084 11085 // At this point, we know that if we shift the LHS up by LHSShift and the 11086 // RHS down by RHSShift, we can emit a regular division with a final scaling 11087 // factor of Scale. 11088 11089 if (LHSShift) 11090 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 11091 DAG.getShiftAmountConstant(LHSShift, VT, dl)); 11092 if (RHSShift) 11093 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 11094 DAG.getShiftAmountConstant(RHSShift, VT, dl)); 11095 11096 SDValue Quot; 11097 if (Signed) { 11098 // For signed operations, if the resulting quotient is negative and the 11099 // remainder is nonzero, subtract 1 from the quotient to round towards 11100 // negative infinity. 11101 SDValue Rem; 11102 // FIXME: Ideally we would always produce an SDIVREM here, but if the 11103 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 11104 // we couldn't just form a libcall, but the type legalizer doesn't do it. 11105 if (isTypeLegal(VT) && 11106 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 11107 Quot = DAG.getNode(ISD::SDIVREM, dl, 11108 DAG.getVTList(VT, VT), 11109 LHS, RHS); 11110 Rem = Quot.getValue(1); 11111 Quot = Quot.getValue(0); 11112 } else { 11113 Quot = DAG.getNode(ISD::SDIV, dl, VT, 11114 LHS, RHS); 11115 Rem = DAG.getNode(ISD::SREM, dl, VT, 11116 LHS, RHS); 11117 } 11118 SDValue Zero = DAG.getConstant(0, dl, VT); 11119 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 11120 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 11121 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 11122 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 11123 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 11124 DAG.getConstant(1, dl, VT)); 11125 Quot = DAG.getSelect(dl, VT, 11126 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 11127 Sub1, Quot); 11128 } else 11129 Quot = DAG.getNode(ISD::UDIV, dl, VT, 11130 LHS, RHS); 11131 11132 return Quot; 11133 } 11134 11135 void TargetLowering::expandUADDSUBO( 11136 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 11137 SDLoc dl(Node); 11138 SDValue LHS = Node->getOperand(0); 11139 SDValue RHS = Node->getOperand(1); 11140 bool IsAdd = Node->getOpcode() == ISD::UADDO; 11141 11142 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead. 11143 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY; 11144 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 11145 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 11146 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 11147 { LHS, RHS, CarryIn }); 11148 Result = SDValue(NodeCarry.getNode(), 0); 11149 Overflow = SDValue(NodeCarry.getNode(), 1); 11150 return; 11151 } 11152 11153 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 11154 LHS.getValueType(), LHS, RHS); 11155 11156 EVT ResultType = Node->getValueType(1); 11157 EVT SetCCType = getSetCCResultType( 11158 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 11159 SDValue SetCC; 11160 if (IsAdd && isOneConstant(RHS)) { 11161 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 11162 // the live range of X. We assume comparing with 0 is cheap. 11163 // The general case (X + C) < C is not necessarily beneficial. Although we 11164 // reduce the live range of X, we may introduce the materialization of 11165 // constant C. 11166 SetCC = 11167 DAG.getSetCC(dl, SetCCType, Result, 11168 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 11169 } else if (IsAdd && isAllOnesConstant(RHS)) { 11170 // Special case: uaddo X, -1 overflows if X != 0. 11171 SetCC = 11172 DAG.getSetCC(dl, SetCCType, LHS, 11173 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE); 11174 } else { 11175 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 11176 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 11177 } 11178 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 11179 } 11180 11181 void TargetLowering::expandSADDSUBO( 11182 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 11183 SDLoc dl(Node); 11184 SDValue LHS = Node->getOperand(0); 11185 SDValue RHS = Node->getOperand(1); 11186 bool IsAdd = Node->getOpcode() == ISD::SADDO; 11187 11188 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 11189 LHS.getValueType(), LHS, RHS); 11190 11191 EVT ResultType = Node->getValueType(1); 11192 EVT OType = getSetCCResultType( 11193 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 11194 11195 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 11196 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 11197 if (isOperationLegal(OpcSat, LHS.getValueType())) { 11198 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 11199 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 11200 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 11201 return; 11202 } 11203 11204 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 11205 11206 // For an addition, the result should be less than one of the operands (LHS) 11207 // if and only if the other operand (RHS) is negative, otherwise there will 11208 // be overflow. 11209 // For a subtraction, the result should be less than one of the operands 11210 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 11211 // otherwise there will be overflow. 11212 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 11213 SDValue ConditionRHS = 11214 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 11215 11216 Overflow = DAG.getBoolExtOrTrunc( 11217 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 11218 ResultType, ResultType); 11219 } 11220 11221 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 11222 SDValue &Overflow, SelectionDAG &DAG) const { 11223 SDLoc dl(Node); 11224 EVT VT = Node->getValueType(0); 11225 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 11226 SDValue LHS = Node->getOperand(0); 11227 SDValue RHS = Node->getOperand(1); 11228 bool isSigned = Node->getOpcode() == ISD::SMULO; 11229 11230 // For power-of-two multiplications we can use a simpler shift expansion. 11231 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 11232 const APInt &C = RHSC->getAPIntValue(); 11233 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 11234 if (C.isPowerOf2()) { 11235 // smulo(x, signed_min) is same as umulo(x, signed_min). 11236 bool UseArithShift = isSigned && !C.isMinSignedValue(); 11237 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl); 11238 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 11239 Overflow = DAG.getSetCC(dl, SetCCVT, 11240 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 11241 dl, VT, Result, ShiftAmt), 11242 LHS, ISD::SETNE); 11243 return true; 11244 } 11245 } 11246 11247 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 11248 if (VT.isVector()) 11249 WideVT = 11250 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 11251 11252 SDValue BottomHalf; 11253 SDValue TopHalf; 11254 static const unsigned Ops[2][3] = 11255 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 11256 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 11257 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 11258 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 11259 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 11260 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 11261 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 11262 RHS); 11263 TopHalf = BottomHalf.getValue(1); 11264 } else if (isTypeLegal(WideVT)) { 11265 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 11266 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 11267 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 11268 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 11269 SDValue ShiftAmt = 11270 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl); 11271 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 11272 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 11273 } else { 11274 if (VT.isVector()) 11275 return false; 11276 11277 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf); 11278 } 11279 11280 Result = BottomHalf; 11281 if (isSigned) { 11282 SDValue ShiftAmt = DAG.getShiftAmountConstant( 11283 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl); 11284 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 11285 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 11286 } else { 11287 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 11288 DAG.getConstant(0, dl, VT), ISD::SETNE); 11289 } 11290 11291 // Truncate the result if SetCC returns a larger type than needed. 11292 EVT RType = Node->getValueType(1); 11293 if (RType.bitsLT(Overflow.getValueType())) 11294 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 11295 11296 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 11297 "Unexpected result type for S/UMULO legalization"); 11298 return true; 11299 } 11300 11301 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 11302 SDLoc dl(Node); 11303 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 11304 SDValue Op = Node->getOperand(0); 11305 EVT VT = Op.getValueType(); 11306 11307 if (VT.isScalableVector()) 11308 report_fatal_error( 11309 "Expanding reductions for scalable vectors is undefined."); 11310 11311 // Try to use a shuffle reduction for power of two vectors. 11312 if (VT.isPow2VectorType()) { 11313 while (VT.getVectorNumElements() > 1) { 11314 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 11315 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 11316 break; 11317 11318 SDValue Lo, Hi; 11319 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 11320 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Node->getFlags()); 11321 VT = HalfVT; 11322 } 11323 } 11324 11325 EVT EltVT = VT.getVectorElementType(); 11326 unsigned NumElts = VT.getVectorNumElements(); 11327 11328 SmallVector<SDValue, 8> Ops; 11329 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 11330 11331 SDValue Res = Ops[0]; 11332 for (unsigned i = 1; i < NumElts; i++) 11333 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 11334 11335 // Result type may be wider than element type. 11336 if (EltVT != Node->getValueType(0)) 11337 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 11338 return Res; 11339 } 11340 11341 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 11342 SDLoc dl(Node); 11343 SDValue AccOp = Node->getOperand(0); 11344 SDValue VecOp = Node->getOperand(1); 11345 SDNodeFlags Flags = Node->getFlags(); 11346 11347 EVT VT = VecOp.getValueType(); 11348 EVT EltVT = VT.getVectorElementType(); 11349 11350 if (VT.isScalableVector()) 11351 report_fatal_error( 11352 "Expanding reductions for scalable vectors is undefined."); 11353 11354 unsigned NumElts = VT.getVectorNumElements(); 11355 11356 SmallVector<SDValue, 8> Ops; 11357 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 11358 11359 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 11360 11361 SDValue Res = AccOp; 11362 for (unsigned i = 0; i < NumElts; i++) 11363 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 11364 11365 return Res; 11366 } 11367 11368 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 11369 SelectionDAG &DAG) const { 11370 EVT VT = Node->getValueType(0); 11371 SDLoc dl(Node); 11372 bool isSigned = Node->getOpcode() == ISD::SREM; 11373 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 11374 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 11375 SDValue Dividend = Node->getOperand(0); 11376 SDValue Divisor = Node->getOperand(1); 11377 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 11378 SDVTList VTs = DAG.getVTList(VT, VT); 11379 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 11380 return true; 11381 } 11382 if (isOperationLegalOrCustom(DivOpc, VT)) { 11383 // X % Y -> X-X/Y*Y 11384 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 11385 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 11386 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 11387 return true; 11388 } 11389 return false; 11390 } 11391 11392 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 11393 SelectionDAG &DAG) const { 11394 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 11395 SDLoc dl(SDValue(Node, 0)); 11396 SDValue Src = Node->getOperand(0); 11397 11398 // DstVT is the result type, while SatVT is the size to which we saturate 11399 EVT SrcVT = Src.getValueType(); 11400 EVT DstVT = Node->getValueType(0); 11401 11402 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 11403 unsigned SatWidth = SatVT.getScalarSizeInBits(); 11404 unsigned DstWidth = DstVT.getScalarSizeInBits(); 11405 assert(SatWidth <= DstWidth && 11406 "Expected saturation width smaller than result width"); 11407 11408 // Determine minimum and maximum integer values and their corresponding 11409 // floating-point values. 11410 APInt MinInt, MaxInt; 11411 if (IsSigned) { 11412 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 11413 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 11414 } else { 11415 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 11416 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 11417 } 11418 11419 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as 11420 // libcall emission cannot handle this. Large result types will fail. 11421 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) { 11422 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 11423 SrcVT = Src.getValueType(); 11424 } 11425 11426 const fltSemantics &Sem = SrcVT.getFltSemantics(); 11427 APFloat MinFloat(Sem); 11428 APFloat MaxFloat(Sem); 11429 11430 APFloat::opStatus MinStatus = 11431 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 11432 APFloat::opStatus MaxStatus = 11433 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 11434 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 11435 !(MaxStatus & APFloat::opStatus::opInexact); 11436 11437 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 11438 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 11439 11440 // If the integer bounds are exactly representable as floats and min/max are 11441 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 11442 // of comparisons and selects. 11443 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 11444 isOperationLegal(ISD::FMAXNUM, SrcVT); 11445 if (AreExactFloatBounds && MinMaxLegal) { 11446 SDValue Clamped = Src; 11447 11448 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 11449 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 11450 // Clamp by MaxFloat from above. NaN cannot occur. 11451 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 11452 // Convert clamped value to integer. 11453 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 11454 dl, DstVT, Clamped); 11455 11456 // In the unsigned case we're done, because we mapped NaN to MinFloat, 11457 // which will cast to zero. 11458 if (!IsSigned) 11459 return FpToInt; 11460 11461 // Otherwise, select 0 if Src is NaN. 11462 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 11463 EVT SetCCVT = 11464 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 11465 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 11466 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt); 11467 } 11468 11469 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 11470 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 11471 11472 // Result of direct conversion. The assumption here is that the operation is 11473 // non-trapping and it's fine to apply it to an out-of-range value if we 11474 // select it away later. 11475 SDValue FpToInt = 11476 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 11477 11478 SDValue Select = FpToInt; 11479 11480 EVT SetCCVT = 11481 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 11482 11483 // If Src ULT MinFloat, select MinInt. In particular, this also selects 11484 // MinInt if Src is NaN. 11485 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT); 11486 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select); 11487 // If Src OGT MaxFloat, select MaxInt. 11488 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT); 11489 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select); 11490 11491 // In the unsigned case we are done, because we mapped NaN to MinInt, which 11492 // is already zero. 11493 if (!IsSigned) 11494 return Select; 11495 11496 // Otherwise, select 0 if Src is NaN. 11497 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 11498 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 11499 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select); 11500 } 11501 11502 SDValue TargetLowering::expandRoundInexactToOdd(EVT ResultVT, SDValue Op, 11503 const SDLoc &dl, 11504 SelectionDAG &DAG) const { 11505 EVT OperandVT = Op.getValueType(); 11506 if (OperandVT.getScalarType() == ResultVT.getScalarType()) 11507 return Op; 11508 EVT ResultIntVT = ResultVT.changeTypeToInteger(); 11509 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This 11510 // can induce double-rounding which may alter the results. We can 11511 // correct for this using a trick explained in: Boldo, Sylvie, and 11512 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS 11513 // World Congress. 2005. 11514 unsigned BitSize = OperandVT.getScalarSizeInBits(); 11515 EVT WideIntVT = OperandVT.changeTypeToInteger(); 11516 SDValue OpAsInt = DAG.getBitcast(WideIntVT, Op); 11517 SDValue SignBit = 11518 DAG.getNode(ISD::AND, dl, WideIntVT, OpAsInt, 11519 DAG.getConstant(APInt::getSignMask(BitSize), dl, WideIntVT)); 11520 SDValue AbsWide; 11521 if (isOperationLegalOrCustom(ISD::FABS, OperandVT)) { 11522 AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op); 11523 } else { 11524 SDValue ClearedSign = DAG.getNode( 11525 ISD::AND, dl, WideIntVT, OpAsInt, 11526 DAG.getConstant(APInt::getSignedMaxValue(BitSize), dl, WideIntVT)); 11527 AbsWide = DAG.getBitcast(OperandVT, ClearedSign); 11528 } 11529 SDValue AbsNarrow = DAG.getFPExtendOrRound(AbsWide, dl, ResultVT); 11530 SDValue AbsNarrowAsWide = DAG.getFPExtendOrRound(AbsNarrow, dl, OperandVT); 11531 11532 // We can keep the narrow value as-is if narrowing was exact (no 11533 // rounding error), the wide value was NaN (the narrow value is also 11534 // NaN and should be preserved) or if we rounded to the odd value. 11535 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, AbsNarrow); 11536 SDValue One = DAG.getConstant(1, dl, ResultIntVT); 11537 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT); 11538 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One); 11539 EVT ResultIntVTCCVT = getSetCCResultType( 11540 DAG.getDataLayout(), *DAG.getContext(), And.getValueType()); 11541 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT); 11542 // The result is already odd so we don't need to do anything. 11543 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE); 11544 11545 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11546 AbsWide.getValueType()); 11547 // We keep results which are exact, odd or NaN. 11548 SDValue KeepNarrow = 11549 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETUEQ); 11550 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd); 11551 // We morally performed a round-down if AbsNarrow is smaller than 11552 // AbsWide. 11553 SDValue NarrowIsRd = 11554 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT); 11555 // If the narrow value is odd or exact, pick it. 11556 // Otherwise, narrow is even and corresponds to either the rounded-up 11557 // or rounded-down value. If narrow is the rounded-down value, we want 11558 // the rounded-up value as it will be odd. 11559 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne); 11560 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust); 11561 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted); 11562 int ShiftAmount = BitSize - ResultVT.getScalarSizeInBits(); 11563 SDValue ShiftCnst = DAG.getShiftAmountConstant(ShiftAmount, WideIntVT, dl); 11564 SignBit = DAG.getNode(ISD::SRL, dl, WideIntVT, SignBit, ShiftCnst); 11565 SignBit = DAG.getNode(ISD::TRUNCATE, dl, ResultIntVT, SignBit); 11566 Op = DAG.getNode(ISD::OR, dl, ResultIntVT, Op, SignBit); 11567 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op); 11568 } 11569 11570 SDValue TargetLowering::expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const { 11571 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!"); 11572 SDValue Op = Node->getOperand(0); 11573 EVT VT = Node->getValueType(0); 11574 SDLoc dl(Node); 11575 if (VT.getScalarType() == MVT::bf16) { 11576 if (Node->getConstantOperandVal(1) == 1) { 11577 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0)); 11578 } 11579 EVT OperandVT = Op.getValueType(); 11580 SDValue IsNaN = DAG.getSetCC( 11581 dl, 11582 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT), 11583 Op, Op, ISD::SETUO); 11584 11585 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This 11586 // can induce double-rounding which may alter the results. We can 11587 // correct for this using a trick explained in: Boldo, Sylvie, and 11588 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS 11589 // World Congress. 2005. 11590 EVT F32 = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32; 11591 EVT I32 = F32.changeTypeToInteger(); 11592 Op = expandRoundInexactToOdd(F32, Op, dl, DAG); 11593 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op); 11594 11595 // Conversions should set NaN's quiet bit. This also prevents NaNs from 11596 // turning into infinities. 11597 SDValue NaN = 11598 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32)); 11599 11600 // Factor in the contribution of the low 16 bits. 11601 SDValue One = DAG.getConstant(1, dl, I32); 11602 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op, 11603 DAG.getShiftAmountConstant(16, I32, dl)); 11604 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One); 11605 SDValue RoundingBias = 11606 DAG.getNode(ISD::ADD, dl, I32, DAG.getConstant(0x7fff, dl, I32), Lsb); 11607 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias); 11608 11609 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into 11610 // 0x80000000. 11611 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add); 11612 11613 // Now that we have rounded, shift the bits into position. 11614 Op = DAG.getNode(ISD::SRL, dl, I32, Op, 11615 DAG.getShiftAmountConstant(16, I32, dl)); 11616 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op); 11617 EVT I16 = I32.isVector() ? I32.changeVectorElementType(MVT::i16) : MVT::i16; 11618 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op); 11619 return DAG.getNode(ISD::BITCAST, dl, VT, Op); 11620 } 11621 return SDValue(); 11622 } 11623 11624 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 11625 SelectionDAG &DAG) const { 11626 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 11627 assert(Node->getValueType(0).isScalableVector() && 11628 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 11629 11630 EVT VT = Node->getValueType(0); 11631 SDValue V1 = Node->getOperand(0); 11632 SDValue V2 = Node->getOperand(1); 11633 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 11634 SDLoc DL(Node); 11635 11636 // Expand through memory thusly: 11637 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 11638 // Store V1, Ptr 11639 // Store V2, Ptr + sizeof(V1) 11640 // If (Imm < 0) 11641 // TrailingElts = -Imm 11642 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 11643 // else 11644 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 11645 // Res = Load Ptr 11646 11647 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 11648 11649 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 11650 VT.getVectorElementCount() * 2); 11651 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 11652 EVT PtrVT = StackPtr.getValueType(); 11653 auto &MF = DAG.getMachineFunction(); 11654 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 11655 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 11656 11657 // Store the lo part of CONCAT_VECTORS(V1, V2) 11658 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 11659 // Store the hi part of CONCAT_VECTORS(V1, V2) 11660 SDValue OffsetToV2 = DAG.getVScale( 11661 DL, PtrVT, 11662 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinValue())); 11663 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 11664 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 11665 11666 if (Imm >= 0) { 11667 // Load back the required element. getVectorElementPointer takes care of 11668 // clamping the index if it's out-of-bounds. 11669 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 11670 // Load the spliced result 11671 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 11672 MachinePointerInfo::getUnknownStack(MF)); 11673 } 11674 11675 uint64_t TrailingElts = -Imm; 11676 11677 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 11678 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 11679 SDValue TrailingBytes = 11680 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 11681 11682 if (TrailingElts > VT.getVectorMinNumElements()) { 11683 SDValue VLBytes = 11684 DAG.getVScale(DL, PtrVT, 11685 APInt(PtrVT.getFixedSizeInBits(), 11686 VT.getStoreSize().getKnownMinValue())); 11687 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 11688 } 11689 11690 // Calculate the start address of the spliced result. 11691 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 11692 11693 // Load the spliced result 11694 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 11695 MachinePointerInfo::getUnknownStack(MF)); 11696 } 11697 11698 SDValue TargetLowering::expandVECTOR_COMPRESS(SDNode *Node, 11699 SelectionDAG &DAG) const { 11700 SDLoc DL(Node); 11701 SDValue Vec = Node->getOperand(0); 11702 SDValue Mask = Node->getOperand(1); 11703 SDValue Passthru = Node->getOperand(2); 11704 11705 EVT VecVT = Vec.getValueType(); 11706 EVT ScalarVT = VecVT.getScalarType(); 11707 EVT MaskVT = Mask.getValueType(); 11708 EVT MaskScalarVT = MaskVT.getScalarType(); 11709 11710 // Needs to be handled by targets that have scalable vector types. 11711 if (VecVT.isScalableVector()) 11712 report_fatal_error("Cannot expand masked_compress for scalable vectors."); 11713 11714 SDValue StackPtr = DAG.CreateStackTemporary( 11715 VecVT.getStoreSize(), DAG.getReducedAlign(VecVT, /*UseABI=*/false)); 11716 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 11717 MachinePointerInfo PtrInfo = 11718 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 11719 11720 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout()); 11721 SDValue Chain = DAG.getEntryNode(); 11722 SDValue OutPos = DAG.getConstant(0, DL, PositionVT); 11723 11724 bool HasPassthru = !Passthru.isUndef(); 11725 11726 // If we have a passthru vector, store it on the stack, overwrite the matching 11727 // positions and then re-write the last element that was potentially 11728 // overwritten even though mask[i] = false. 11729 if (HasPassthru) 11730 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo); 11731 11732 SDValue LastWriteVal; 11733 APInt PassthruSplatVal; 11734 bool IsSplatPassthru = 11735 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal); 11736 11737 if (IsSplatPassthru) { 11738 // As we do not know which position we wrote to last, we cannot simply 11739 // access that index from the passthru vector. So we first check if passthru 11740 // is a splat vector, to use any element ... 11741 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT); 11742 } else if (HasPassthru) { 11743 // ... if it is not a splat vector, we need to get the passthru value at 11744 // position = popcount(mask) and re-load it from the stack before it is 11745 // overwritten in the loop below. 11746 EVT PopcountVT = ScalarVT.changeTypeToInteger(); 11747 SDValue Popcount = DAG.getNode( 11748 ISD::TRUNCATE, DL, MaskVT.changeVectorElementType(MVT::i1), Mask); 11749 Popcount = 11750 DAG.getNode(ISD::ZERO_EXTEND, DL, 11751 MaskVT.changeVectorElementType(PopcountVT), Popcount); 11752 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount); 11753 SDValue LastElmtPtr = 11754 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount); 11755 LastWriteVal = DAG.getLoad( 11756 ScalarVT, DL, Chain, LastElmtPtr, 11757 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11758 Chain = LastWriteVal.getValue(1); 11759 } 11760 11761 unsigned NumElms = VecVT.getVectorNumElements(); 11762 for (unsigned I = 0; I < NumElms; I++) { 11763 SDValue Idx = DAG.getVectorIdxConstant(I, DL); 11764 11765 SDValue ValI = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Vec, Idx); 11766 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos); 11767 Chain = DAG.getStore( 11768 Chain, DL, ValI, OutPtr, 11769 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11770 11771 // Get the mask value and add it to the current output position. This 11772 // either increments by 1 if MaskI is true or adds 0 otherwise. 11773 // Freeze in case we have poison/undef mask entries. 11774 SDValue MaskI = DAG.getFreeze( 11775 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskScalarVT, Mask, Idx)); 11776 MaskI = DAG.getFreeze(MaskI); 11777 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI); 11778 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI); 11779 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI); 11780 11781 if (HasPassthru && I == NumElms - 1) { 11782 SDValue EndOfVector = 11783 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT); 11784 SDValue AllLanesSelected = 11785 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT); 11786 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector); 11787 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos); 11788 11789 // Re-write the last ValI if all lanes were selected. Otherwise, 11790 // overwrite the last write it with the passthru value. 11791 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI, 11792 LastWriteVal, SDNodeFlags::Unpredictable); 11793 Chain = DAG.getStore( 11794 Chain, DL, LastWriteVal, OutPtr, 11795 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 11796 } 11797 } 11798 11799 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo); 11800 } 11801 11802 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 11803 SDValue &LHS, SDValue &RHS, 11804 SDValue &CC, SDValue Mask, 11805 SDValue EVL, bool &NeedInvert, 11806 const SDLoc &dl, SDValue &Chain, 11807 bool IsSignaling) const { 11808 MVT OpVT = LHS.getSimpleValueType(); 11809 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 11810 NeedInvert = false; 11811 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 11812 bool IsNonVP = !EVL; 11813 switch (getCondCodeAction(CCCode, OpVT)) { 11814 default: 11815 llvm_unreachable("Unknown condition code action!"); 11816 case TargetLowering::Legal: 11817 // Nothing to do. 11818 break; 11819 case TargetLowering::Expand: { 11820 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 11821 if (isCondCodeLegalOrCustom(InvCC, OpVT)) { 11822 std::swap(LHS, RHS); 11823 CC = DAG.getCondCode(InvCC); 11824 return true; 11825 } 11826 // Swapping operands didn't work. Try inverting the condition. 11827 bool NeedSwap = false; 11828 InvCC = getSetCCInverse(CCCode, OpVT); 11829 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) { 11830 // If inverting the condition is not enough, try swapping operands 11831 // on top of it. 11832 InvCC = ISD::getSetCCSwappedOperands(InvCC); 11833 NeedSwap = true; 11834 } 11835 if (isCondCodeLegalOrCustom(InvCC, OpVT)) { 11836 CC = DAG.getCondCode(InvCC); 11837 NeedInvert = true; 11838 if (NeedSwap) 11839 std::swap(LHS, RHS); 11840 return true; 11841 } 11842 11843 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 11844 unsigned Opc = 0; 11845 switch (CCCode) { 11846 default: 11847 llvm_unreachable("Don't know how to expand this condition!"); 11848 case ISD::SETUO: 11849 if (isCondCodeLegal(ISD::SETUNE, OpVT)) { 11850 CC1 = ISD::SETUNE; 11851 CC2 = ISD::SETUNE; 11852 Opc = ISD::OR; 11853 break; 11854 } 11855 assert(isCondCodeLegal(ISD::SETOEQ, OpVT) && 11856 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 11857 NeedInvert = true; 11858 [[fallthrough]]; 11859 case ISD::SETO: 11860 assert(isCondCodeLegal(ISD::SETOEQ, OpVT) && 11861 "If SETO is expanded, SETOEQ must be legal!"); 11862 CC1 = ISD::SETOEQ; 11863 CC2 = ISD::SETOEQ; 11864 Opc = ISD::AND; 11865 break; 11866 case ISD::SETONE: 11867 case ISD::SETUEQ: 11868 // If the SETUO or SETO CC isn't legal, we might be able to use 11869 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 11870 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 11871 // the operands. 11872 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 11873 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) || 11874 isCondCodeLegal(ISD::SETOLT, OpVT))) { 11875 CC1 = ISD::SETOGT; 11876 CC2 = ISD::SETOLT; 11877 Opc = ISD::OR; 11878 NeedInvert = ((unsigned)CCCode & 0x8U); 11879 break; 11880 } 11881 [[fallthrough]]; 11882 case ISD::SETOEQ: 11883 case ISD::SETOGT: 11884 case ISD::SETOGE: 11885 case ISD::SETOLT: 11886 case ISD::SETOLE: 11887 case ISD::SETUNE: 11888 case ISD::SETUGT: 11889 case ISD::SETUGE: 11890 case ISD::SETULT: 11891 case ISD::SETULE: 11892 // If we are floating point, assign and break, otherwise fall through. 11893 if (!OpVT.isInteger()) { 11894 // We can use the 4th bit to tell if we are the unordered 11895 // or ordered version of the opcode. 11896 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 11897 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 11898 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 11899 break; 11900 } 11901 // Fallthrough if we are unsigned integer. 11902 [[fallthrough]]; 11903 case ISD::SETLE: 11904 case ISD::SETGT: 11905 case ISD::SETGE: 11906 case ISD::SETLT: 11907 case ISD::SETNE: 11908 case ISD::SETEQ: 11909 // If all combinations of inverting the condition and swapping operands 11910 // didn't work then we have no means to expand the condition. 11911 llvm_unreachable("Don't know how to expand this condition!"); 11912 } 11913 11914 SDValue SetCC1, SetCC2; 11915 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 11916 // If we aren't the ordered or unorder operation, 11917 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 11918 if (IsNonVP) { 11919 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 11920 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 11921 } else { 11922 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 11923 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 11924 } 11925 } else { 11926 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 11927 if (IsNonVP) { 11928 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 11929 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 11930 } else { 11931 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 11932 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 11933 } 11934 } 11935 if (Chain) 11936 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 11937 SetCC2.getValue(1)); 11938 if (IsNonVP) 11939 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 11940 else { 11941 // Transform the binary opcode to the VP equivalent. 11942 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 11943 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 11944 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 11945 } 11946 RHS = SDValue(); 11947 CC = SDValue(); 11948 return true; 11949 } 11950 } 11951 return false; 11952 } 11953 11954 SDValue TargetLowering::expandVectorNaryOpBySplitting(SDNode *Node, 11955 SelectionDAG &DAG) const { 11956 EVT VT = Node->getValueType(0); 11957 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be 11958 // split into two equal parts. 11959 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2)) 11960 return SDValue(); 11961 11962 // Restrict expansion to cases where both parts can be concatenated. 11963 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT); 11964 if (LoVT != HiVT || !isTypeLegal(LoVT)) 11965 return SDValue(); 11966 11967 SDLoc DL(Node); 11968 unsigned Opcode = Node->getOpcode(); 11969 11970 // Don't expand if the result is likely to be unrolled anyway. 11971 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT)) 11972 return SDValue(); 11973 11974 SmallVector<SDValue, 4> LoOps, HiOps; 11975 for (const SDValue &V : Node->op_values()) { 11976 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT); 11977 LoOps.push_back(Lo); 11978 HiOps.push_back(Hi); 11979 } 11980 11981 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps); 11982 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps); 11983 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi); 11984 } 11985