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/CodeGen/CallingConvLower.h" 16 #include "llvm/CodeGen/CodeGenCommonISel.h" 17 #include "llvm/CodeGen/MachineFrameInfo.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineJumpTableInfo.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/SelectionDAG.h" 22 #include "llvm/CodeGen/TargetRegisterInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/Support/DivisionByConstantInfo.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/KnownBits.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include <cctype> 35 using namespace llvm; 36 37 /// NOTE: The TargetMachine owns TLOF. 38 TargetLowering::TargetLowering(const TargetMachine &tm) 39 : TargetLoweringBase(tm) {} 40 41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 42 return nullptr; 43 } 44 45 bool TargetLowering::isPositionIndependent() const { 46 return getTargetMachine().isPositionIndependent(); 47 } 48 49 /// Check whether a given call node is in tail position within its function. If 50 /// so, it sets Chain to the input chain of the tail call. 51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 52 SDValue &Chain) const { 53 const Function &F = DAG.getMachineFunction().getFunction(); 54 55 // First, check if tail calls have been disabled in this function. 56 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 57 return false; 58 59 // Conservatively require the attributes of the call to match those of 60 // the return. Ignore following attributes because they don't affect the 61 // call sequence. 62 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 63 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable, 64 Attribute::DereferenceableOrNull, Attribute::NoAlias, 65 Attribute::NonNull, Attribute::NoUndef}) 66 CallerAttrs.removeAttribute(Attr); 67 68 if (CallerAttrs.hasAttributes()) 69 return false; 70 71 // It's not safe to eliminate the sign / zero extension of the return value. 72 if (CallerAttrs.contains(Attribute::ZExt) || 73 CallerAttrs.contains(Attribute::SExt)) 74 return false; 75 76 // Check if the only use is a function return node. 77 return isUsedByReturnOnly(Node, Chain); 78 } 79 80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 81 const uint32_t *CallerPreservedMask, 82 const SmallVectorImpl<CCValAssign> &ArgLocs, 83 const SmallVectorImpl<SDValue> &OutVals) const { 84 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 85 const CCValAssign &ArgLoc = ArgLocs[I]; 86 if (!ArgLoc.isRegLoc()) 87 continue; 88 MCRegister Reg = ArgLoc.getLocReg(); 89 // Only look at callee saved registers. 90 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 91 continue; 92 // Check that we pass the value used for the caller. 93 // (We look for a CopyFromReg reading a virtual register that is used 94 // for the function live-in value of register Reg) 95 SDValue Value = OutVals[I]; 96 if (Value->getOpcode() == ISD::AssertZext) 97 Value = Value.getOperand(0); 98 if (Value->getOpcode() != ISD::CopyFromReg) 99 return false; 100 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 101 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 102 return false; 103 } 104 return true; 105 } 106 107 /// Set CallLoweringInfo attribute flags based on a call instruction 108 /// and called function attributes. 109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 110 unsigned ArgIdx) { 111 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 112 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 113 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 114 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 115 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 116 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 117 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 118 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 119 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 120 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 121 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 122 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 123 Alignment = Call->getParamStackAlign(ArgIdx); 124 IndirectType = nullptr; 125 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 126 "multiple ABI attributes?"); 127 if (IsByVal) { 128 IndirectType = Call->getParamByValType(ArgIdx); 129 if (!Alignment) 130 Alignment = Call->getParamAlign(ArgIdx); 131 } 132 if (IsPreallocated) 133 IndirectType = Call->getParamPreallocatedType(ArgIdx); 134 if (IsInAlloca) 135 IndirectType = Call->getParamInAllocaType(ArgIdx); 136 if (IsSRet) 137 IndirectType = Call->getParamStructRetType(ArgIdx); 138 } 139 140 /// Generate a libcall taking the given operands as arguments and returning a 141 /// result of type RetVT. 142 std::pair<SDValue, SDValue> 143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 144 ArrayRef<SDValue> Ops, 145 MakeLibCallOptions CallOptions, 146 const SDLoc &dl, 147 SDValue InChain) const { 148 if (!InChain) 149 InChain = DAG.getEntryNode(); 150 151 TargetLowering::ArgListTy Args; 152 Args.reserve(Ops.size()); 153 154 TargetLowering::ArgListEntry Entry; 155 for (unsigned i = 0; i < Ops.size(); ++i) { 156 SDValue NewOp = Ops[i]; 157 Entry.Node = NewOp; 158 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 159 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 160 CallOptions.IsSExt); 161 Entry.IsZExt = !Entry.IsSExt; 162 163 if (CallOptions.IsSoften && 164 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 165 Entry.IsSExt = Entry.IsZExt = false; 166 } 167 Args.push_back(Entry); 168 } 169 170 if (LC == RTLIB::UNKNOWN_LIBCALL) 171 report_fatal_error("Unsupported library call operation!"); 172 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 173 getPointerTy(DAG.getDataLayout())); 174 175 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 176 TargetLowering::CallLoweringInfo CLI(DAG); 177 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 178 bool zeroExtend = !signExtend; 179 180 if (CallOptions.IsSoften && 181 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 182 signExtend = zeroExtend = false; 183 } 184 185 CLI.setDebugLoc(dl) 186 .setChain(InChain) 187 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 188 .setNoReturn(CallOptions.DoesNotReturn) 189 .setDiscardResult(!CallOptions.IsReturnValueUsed) 190 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 191 .setSExtResult(signExtend) 192 .setZExtResult(zeroExtend); 193 return LowerCallTo(CLI); 194 } 195 196 bool TargetLowering::findOptimalMemOpLowering( 197 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 198 unsigned SrcAS, const AttributeList &FuncAttributes) const { 199 if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() && 200 Op.getSrcAlign() < Op.getDstAlign()) 201 return false; 202 203 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 204 205 if (VT == MVT::Other) { 206 // Use the largest integer type whose alignment constraints are satisfied. 207 // We only need to check DstAlign here as SrcAlign is always greater or 208 // equal to DstAlign (or zero). 209 VT = MVT::i64; 210 if (Op.isFixedDstAlign()) 211 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 212 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 213 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 214 assert(VT.isInteger()); 215 216 // Find the largest legal integer type. 217 MVT LVT = MVT::i64; 218 while (!isTypeLegal(LVT)) 219 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 220 assert(LVT.isInteger()); 221 222 // If the type we've chosen is larger than the largest legal integer type 223 // then use that instead. 224 if (VT.bitsGT(LVT)) 225 VT = LVT; 226 } 227 228 unsigned NumMemOps = 0; 229 uint64_t Size = Op.size(); 230 while (Size) { 231 unsigned VTSize = VT.getSizeInBits() / 8; 232 while (VTSize > Size) { 233 // For now, only use non-vector load / store's for the left-over pieces. 234 EVT NewVT = VT; 235 unsigned NewVTSize; 236 237 bool Found = false; 238 if (VT.isVector() || VT.isFloatingPoint()) { 239 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 240 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 241 isSafeMemOpType(NewVT.getSimpleVT())) 242 Found = true; 243 else if (NewVT == MVT::i64 && 244 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 245 isSafeMemOpType(MVT::f64)) { 246 // i64 is usually not legal on 32-bit targets, but f64 may be. 247 NewVT = MVT::f64; 248 Found = true; 249 } 250 } 251 252 if (!Found) { 253 do { 254 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 255 if (NewVT == MVT::i8) 256 break; 257 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 258 } 259 NewVTSize = NewVT.getSizeInBits() / 8; 260 261 // If the new VT cannot cover all of the remaining bits, then consider 262 // issuing a (or a pair of) unaligned and overlapping load / store. 263 bool Fast; 264 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 265 allowsMisalignedMemoryAccesses( 266 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 267 MachineMemOperand::MONone, &Fast) && 268 Fast) 269 VTSize = Size; 270 else { 271 VT = NewVT; 272 VTSize = NewVTSize; 273 } 274 } 275 276 if (++NumMemOps > Limit) 277 return false; 278 279 MemOps.push_back(VT); 280 Size -= VTSize; 281 } 282 283 return true; 284 } 285 286 /// Soften the operands of a comparison. This code is shared among BR_CC, 287 /// SELECT_CC, and SETCC handlers. 288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 289 SDValue &NewLHS, SDValue &NewRHS, 290 ISD::CondCode &CCCode, 291 const SDLoc &dl, const SDValue OldLHS, 292 const SDValue OldRHS) const { 293 SDValue Chain; 294 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 295 OldRHS, Chain); 296 } 297 298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 299 SDValue &NewLHS, SDValue &NewRHS, 300 ISD::CondCode &CCCode, 301 const SDLoc &dl, const SDValue OldLHS, 302 const SDValue OldRHS, 303 SDValue &Chain, 304 bool IsSignaling) const { 305 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 306 // not supporting it. We can update this code when libgcc provides such 307 // functions. 308 309 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 310 && "Unsupported setcc type!"); 311 312 // Expand into one or more soft-fp libcall(s). 313 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 314 bool ShouldInvertCC = false; 315 switch (CCCode) { 316 case ISD::SETEQ: 317 case ISD::SETOEQ: 318 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 319 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 320 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 321 break; 322 case ISD::SETNE: 323 case ISD::SETUNE: 324 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 325 (VT == MVT::f64) ? RTLIB::UNE_F64 : 326 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 327 break; 328 case ISD::SETGE: 329 case ISD::SETOGE: 330 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 331 (VT == MVT::f64) ? RTLIB::OGE_F64 : 332 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 333 break; 334 case ISD::SETLT: 335 case ISD::SETOLT: 336 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 337 (VT == MVT::f64) ? RTLIB::OLT_F64 : 338 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 339 break; 340 case ISD::SETLE: 341 case ISD::SETOLE: 342 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 343 (VT == MVT::f64) ? RTLIB::OLE_F64 : 344 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 345 break; 346 case ISD::SETGT: 347 case ISD::SETOGT: 348 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 349 (VT == MVT::f64) ? RTLIB::OGT_F64 : 350 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 351 break; 352 case ISD::SETO: 353 ShouldInvertCC = true; 354 LLVM_FALLTHROUGH; 355 case ISD::SETUO: 356 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 357 (VT == MVT::f64) ? RTLIB::UO_F64 : 358 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 359 break; 360 case ISD::SETONE: 361 // SETONE = O && UNE 362 ShouldInvertCC = true; 363 LLVM_FALLTHROUGH; 364 case ISD::SETUEQ: 365 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 366 (VT == MVT::f64) ? RTLIB::UO_F64 : 367 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 368 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 369 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 370 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 371 break; 372 default: 373 // Invert CC for unordered comparisons 374 ShouldInvertCC = true; 375 switch (CCCode) { 376 case ISD::SETULT: 377 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 378 (VT == MVT::f64) ? RTLIB::OGE_F64 : 379 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 380 break; 381 case ISD::SETULE: 382 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 383 (VT == MVT::f64) ? RTLIB::OGT_F64 : 384 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 385 break; 386 case ISD::SETUGT: 387 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 388 (VT == MVT::f64) ? RTLIB::OLE_F64 : 389 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 390 break; 391 case ISD::SETUGE: 392 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 393 (VT == MVT::f64) ? RTLIB::OLT_F64 : 394 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 395 break; 396 default: llvm_unreachable("Do not know how to soften this setcc!"); 397 } 398 } 399 400 // Use the target specific return value for comparions lib calls. 401 EVT RetVT = getCmpLibcallReturnType(); 402 SDValue Ops[2] = {NewLHS, NewRHS}; 403 TargetLowering::MakeLibCallOptions CallOptions; 404 EVT OpsVT[2] = { OldLHS.getValueType(), 405 OldRHS.getValueType() }; 406 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 407 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 408 NewLHS = Call.first; 409 NewRHS = DAG.getConstant(0, dl, RetVT); 410 411 CCCode = getCmpLibcallCC(LC1); 412 if (ShouldInvertCC) { 413 assert(RetVT.isInteger()); 414 CCCode = getSetCCInverse(CCCode, RetVT); 415 } 416 417 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 418 // Update Chain. 419 Chain = Call.second; 420 } else { 421 EVT SetCCVT = 422 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 423 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 424 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 425 CCCode = getCmpLibcallCC(LC2); 426 if (ShouldInvertCC) 427 CCCode = getSetCCInverse(CCCode, RetVT); 428 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 429 if (Chain) 430 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 431 Call2.second); 432 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 433 Tmp.getValueType(), Tmp, NewLHS); 434 NewRHS = SDValue(); 435 } 436 } 437 438 /// Return the entry encoding for a jump table in the current function. The 439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 440 unsigned TargetLowering::getJumpTableEncoding() const { 441 // In non-pic modes, just use the address of a block. 442 if (!isPositionIndependent()) 443 return MachineJumpTableInfo::EK_BlockAddress; 444 445 // In PIC mode, if the target supports a GPRel32 directive, use it. 446 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 447 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 448 449 // Otherwise, use a label difference. 450 return MachineJumpTableInfo::EK_LabelDifference32; 451 } 452 453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 454 SelectionDAG &DAG) const { 455 // If our PIC model is GP relative, use the global offset table as the base. 456 unsigned JTEncoding = getJumpTableEncoding(); 457 458 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 459 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 460 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 461 462 return Table; 463 } 464 465 /// This returns the relocation base for the given PIC jumptable, the same as 466 /// getPICJumpTableRelocBase, but as an MCExpr. 467 const MCExpr * 468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 469 unsigned JTI,MCContext &Ctx) const{ 470 // The normal PIC reloc base is the label at the start of the jump table. 471 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 472 } 473 474 bool 475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 476 const TargetMachine &TM = getTargetMachine(); 477 const GlobalValue *GV = GA->getGlobal(); 478 479 // If the address is not even local to this DSO we will have to load it from 480 // a got and then add the offset. 481 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 482 return false; 483 484 // If the code is position independent we will have to add a base register. 485 if (isPositionIndependent()) 486 return false; 487 488 // Otherwise we can do it. 489 return true; 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Optimization Methods 494 //===----------------------------------------------------------------------===// 495 496 /// If the specified instruction has a constant integer operand and there are 497 /// bits set in that constant that are not demanded, then clear those bits and 498 /// return true. 499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 500 const APInt &DemandedBits, 501 const APInt &DemandedElts, 502 TargetLoweringOpt &TLO) const { 503 SDLoc DL(Op); 504 unsigned Opcode = Op.getOpcode(); 505 506 // Do target-specific constant optimization. 507 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 508 return TLO.New.getNode(); 509 510 // FIXME: ISD::SELECT, ISD::SELECT_CC 511 switch (Opcode) { 512 default: 513 break; 514 case ISD::XOR: 515 case ISD::AND: 516 case ISD::OR: { 517 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 518 if (!Op1C || Op1C->isOpaque()) 519 return false; 520 521 // If this is a 'not' op, don't touch it because that's a canonical form. 522 const APInt &C = Op1C->getAPIntValue(); 523 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 524 return false; 525 526 if (!C.isSubsetOf(DemandedBits)) { 527 EVT VT = Op.getValueType(); 528 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 529 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 530 return TLO.CombineTo(Op, NewOp); 531 } 532 533 break; 534 } 535 } 536 537 return false; 538 } 539 540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 541 const APInt &DemandedBits, 542 TargetLoweringOpt &TLO) const { 543 EVT VT = Op.getValueType(); 544 APInt DemandedElts = VT.isVector() 545 ? APInt::getAllOnes(VT.getVectorNumElements()) 546 : APInt(1, 1); 547 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 548 } 549 550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 552 /// generalized for targets with other types of implicit widening casts. 553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 554 const APInt &Demanded, 555 TargetLoweringOpt &TLO) const { 556 assert(Op.getNumOperands() == 2 && 557 "ShrinkDemandedOp only supports binary operators!"); 558 assert(Op.getNode()->getNumValues() == 1 && 559 "ShrinkDemandedOp only supports nodes with one result!"); 560 561 SelectionDAG &DAG = TLO.DAG; 562 SDLoc dl(Op); 563 564 // Early return, as this function cannot handle vector types. 565 if (Op.getValueType().isVector()) 566 return false; 567 568 // Don't do this if the node has another user, which may require the 569 // full value. 570 if (!Op.getNode()->hasOneUse()) 571 return false; 572 573 // Search for the smallest integer type with free casts to and from 574 // Op's type. For expedience, just check power-of-2 integer types. 575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 576 unsigned DemandedSize = Demanded.getActiveBits(); 577 unsigned SmallVTBits = DemandedSize; 578 if (!isPowerOf2_32(SmallVTBits)) 579 SmallVTBits = NextPowerOf2(SmallVTBits); 580 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 581 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 582 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 583 TLI.isZExtFree(SmallVT, Op.getValueType())) { 584 // We found a type with free casts. 585 SDValue X = DAG.getNode( 586 Op.getOpcode(), dl, SmallVT, 587 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 588 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 589 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 590 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 591 return TLO.CombineTo(Op, Z); 592 } 593 } 594 return false; 595 } 596 597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 598 DAGCombinerInfo &DCI) const { 599 SelectionDAG &DAG = DCI.DAG; 600 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 601 !DCI.isBeforeLegalizeOps()); 602 KnownBits Known; 603 604 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 605 if (Simplified) { 606 DCI.AddToWorklist(Op.getNode()); 607 DCI.CommitTargetLoweringOpt(TLO); 608 } 609 return Simplified; 610 } 611 612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 613 const APInt &DemandedElts, 614 DAGCombinerInfo &DCI) const { 615 SelectionDAG &DAG = DCI.DAG; 616 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 617 !DCI.isBeforeLegalizeOps()); 618 KnownBits Known; 619 620 bool Simplified = 621 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 622 if (Simplified) { 623 DCI.AddToWorklist(Op.getNode()); 624 DCI.CommitTargetLoweringOpt(TLO); 625 } 626 return Simplified; 627 } 628 629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 630 KnownBits &Known, 631 TargetLoweringOpt &TLO, 632 unsigned Depth, 633 bool AssumeSingleUse) const { 634 EVT VT = Op.getValueType(); 635 636 // TODO: We can probably do more work on calculating the known bits and 637 // simplifying the operations for scalable vectors, but for now we just 638 // bail out. 639 if (VT.isScalableVector()) { 640 // Pretend we don't know anything for now. 641 Known = KnownBits(DemandedBits.getBitWidth()); 642 return false; 643 } 644 645 APInt DemandedElts = VT.isVector() 646 ? APInt::getAllOnes(VT.getVectorNumElements()) 647 : APInt(1, 1); 648 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 649 AssumeSingleUse); 650 } 651 652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 653 // TODO: Under what circumstances can we create nodes? Constant folding? 654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 655 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 656 SelectionDAG &DAG, unsigned Depth) const { 657 // Limit search depth. 658 if (Depth >= SelectionDAG::MaxRecursionDepth) 659 return SDValue(); 660 661 // Ignore UNDEFs. 662 if (Op.isUndef()) 663 return SDValue(); 664 665 // Not demanding any bits/elts from Op. 666 if (DemandedBits == 0 || DemandedElts == 0) 667 return DAG.getUNDEF(Op.getValueType()); 668 669 bool IsLE = DAG.getDataLayout().isLittleEndian(); 670 unsigned NumElts = DemandedElts.getBitWidth(); 671 unsigned BitWidth = DemandedBits.getBitWidth(); 672 KnownBits LHSKnown, RHSKnown; 673 switch (Op.getOpcode()) { 674 case ISD::BITCAST: { 675 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 676 EVT SrcVT = Src.getValueType(); 677 EVT DstVT = Op.getValueType(); 678 if (SrcVT == DstVT) 679 return Src; 680 681 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 682 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 683 if (NumSrcEltBits == NumDstEltBits) 684 if (SDValue V = SimplifyMultipleUseDemandedBits( 685 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 686 return DAG.getBitcast(DstVT, V); 687 688 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 689 unsigned Scale = NumDstEltBits / NumSrcEltBits; 690 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 691 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 692 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 693 for (unsigned i = 0; i != Scale; ++i) { 694 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 695 unsigned BitOffset = EltOffset * NumSrcEltBits; 696 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 697 if (!Sub.isZero()) { 698 DemandedSrcBits |= Sub; 699 for (unsigned j = 0; j != NumElts; ++j) 700 if (DemandedElts[j]) 701 DemandedSrcElts.setBit((j * Scale) + i); 702 } 703 } 704 705 if (SDValue V = SimplifyMultipleUseDemandedBits( 706 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 707 return DAG.getBitcast(DstVT, V); 708 } 709 710 // TODO - bigendian once we have test coverage. 711 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 712 unsigned Scale = NumSrcEltBits / NumDstEltBits; 713 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 714 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 715 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 716 for (unsigned i = 0; i != NumElts; ++i) 717 if (DemandedElts[i]) { 718 unsigned Offset = (i % Scale) * NumDstEltBits; 719 DemandedSrcBits.insertBits(DemandedBits, Offset); 720 DemandedSrcElts.setBit(i / Scale); 721 } 722 723 if (SDValue V = SimplifyMultipleUseDemandedBits( 724 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 725 return DAG.getBitcast(DstVT, V); 726 } 727 728 break; 729 } 730 case ISD::AND: { 731 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 732 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 733 734 // If all of the demanded bits are known 1 on one side, return the other. 735 // These bits cannot contribute to the result of the 'and' in this 736 // context. 737 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 738 return Op.getOperand(0); 739 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 740 return Op.getOperand(1); 741 break; 742 } 743 case ISD::OR: { 744 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 745 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 746 747 // If all of the demanded bits are known zero on one side, return the 748 // other. These bits cannot contribute to the result of the 'or' in this 749 // context. 750 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 751 return Op.getOperand(0); 752 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 753 return Op.getOperand(1); 754 break; 755 } 756 case ISD::XOR: { 757 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 758 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 759 760 // If all of the demanded bits are known zero on one side, return the 761 // other. 762 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 763 return Op.getOperand(0); 764 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 765 return Op.getOperand(1); 766 break; 767 } 768 case ISD::SHL: { 769 // If we are only demanding sign bits then we can use the shift source 770 // directly. 771 if (const APInt *MaxSA = 772 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 773 SDValue Op0 = Op.getOperand(0); 774 unsigned ShAmt = MaxSA->getZExtValue(); 775 unsigned NumSignBits = 776 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 777 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 778 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 779 return Op0; 780 } 781 break; 782 } 783 case ISD::SETCC: { 784 SDValue Op0 = Op.getOperand(0); 785 SDValue Op1 = Op.getOperand(1); 786 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 787 // If (1) we only need the sign-bit, (2) the setcc operands are the same 788 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 789 // -1, we may be able to bypass the setcc. 790 if (DemandedBits.isSignMask() && 791 Op0.getScalarValueSizeInBits() == BitWidth && 792 getBooleanContents(Op0.getValueType()) == 793 BooleanContent::ZeroOrNegativeOneBooleanContent) { 794 // If we're testing X < 0, then this compare isn't needed - just use X! 795 // FIXME: We're limiting to integer types here, but this should also work 796 // if we don't care about FP signed-zero. The use of SETLT with FP means 797 // that we don't care about NaNs. 798 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 799 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 800 return Op0; 801 } 802 break; 803 } 804 case ISD::SIGN_EXTEND_INREG: { 805 // If none of the extended bits are demanded, eliminate the sextinreg. 806 SDValue Op0 = Op.getOperand(0); 807 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 808 unsigned ExBits = ExVT.getScalarSizeInBits(); 809 if (DemandedBits.getActiveBits() <= ExBits) 810 return Op0; 811 // If the input is already sign extended, just drop the extension. 812 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 813 if (NumSignBits >= (BitWidth - ExBits + 1)) 814 return Op0; 815 break; 816 } 817 case ISD::ANY_EXTEND_VECTOR_INREG: 818 case ISD::SIGN_EXTEND_VECTOR_INREG: 819 case ISD::ZERO_EXTEND_VECTOR_INREG: { 820 // If we only want the lowest element and none of extended bits, then we can 821 // return the bitcasted source vector. 822 SDValue Src = Op.getOperand(0); 823 EVT SrcVT = Src.getValueType(); 824 EVT DstVT = Op.getValueType(); 825 if (IsLE && DemandedElts == 1 && 826 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 827 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 828 return DAG.getBitcast(DstVT, Src); 829 } 830 break; 831 } 832 case ISD::INSERT_VECTOR_ELT: { 833 // If we don't demand the inserted element, return the base vector. 834 SDValue Vec = Op.getOperand(0); 835 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 836 EVT VecVT = Vec.getValueType(); 837 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 838 !DemandedElts[CIdx->getZExtValue()]) 839 return Vec; 840 break; 841 } 842 case ISD::INSERT_SUBVECTOR: { 843 SDValue Vec = Op.getOperand(0); 844 SDValue Sub = Op.getOperand(1); 845 uint64_t Idx = Op.getConstantOperandVal(2); 846 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 847 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 848 // If we don't demand the inserted subvector, return the base vector. 849 if (DemandedSubElts == 0) 850 return Vec; 851 // If this simply widens the lowest subvector, see if we can do it earlier. 852 if (Idx == 0 && Vec.isUndef()) { 853 if (SDValue NewSub = SimplifyMultipleUseDemandedBits( 854 Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1)) 855 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 856 Op.getOperand(0), NewSub, Op.getOperand(2)); 857 } 858 break; 859 } 860 case ISD::VECTOR_SHUFFLE: { 861 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 862 863 // If all the demanded elts are from one operand and are inline, 864 // then we can use the operand directly. 865 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 866 for (unsigned i = 0; i != NumElts; ++i) { 867 int M = ShuffleMask[i]; 868 if (M < 0 || !DemandedElts[i]) 869 continue; 870 AllUndef = false; 871 IdentityLHS &= (M == (int)i); 872 IdentityRHS &= ((M - NumElts) == i); 873 } 874 875 if (AllUndef) 876 return DAG.getUNDEF(Op.getValueType()); 877 if (IdentityLHS) 878 return Op.getOperand(0); 879 if (IdentityRHS) 880 return Op.getOperand(1); 881 break; 882 } 883 default: 884 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 885 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 886 Op, DemandedBits, DemandedElts, DAG, Depth)) 887 return V; 888 break; 889 } 890 return SDValue(); 891 } 892 893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 894 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 895 unsigned Depth) const { 896 EVT VT = Op.getValueType(); 897 APInt DemandedElts = VT.isVector() 898 ? APInt::getAllOnes(VT.getVectorNumElements()) 899 : APInt(1, 1); 900 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 901 Depth); 902 } 903 904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 905 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 906 unsigned Depth) const { 907 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 908 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 909 Depth); 910 } 911 912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 913 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG, 915 const TargetLowering &TLI, 916 const APInt &DemandedBits, 917 const APInt &DemandedElts, 918 unsigned Depth) { 919 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 920 "SRL or SRA node is required here!"); 921 // Is the right shift using an immediate value of 1? 922 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 923 if (!N1C || !N1C->isOne()) 924 return SDValue(); 925 926 // We are looking for an avgfloor 927 // add(ext, ext) 928 // or one of these as a avgceil 929 // add(add(ext, ext), 1) 930 // add(add(ext, 1), ext) 931 // add(ext, add(ext, 1)) 932 SDValue Add = Op.getOperand(0); 933 if (Add.getOpcode() != ISD::ADD) 934 return SDValue(); 935 936 SDValue ExtOpA = Add.getOperand(0); 937 SDValue ExtOpB = Add.getOperand(1); 938 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) { 939 ConstantSDNode *ConstOp; 940 if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) && 941 ConstOp->isOne()) { 942 ExtOpA = Op2; 943 ExtOpB = Op3; 944 return true; 945 } 946 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 947 ConstOp->isOne()) { 948 ExtOpA = Op1; 949 ExtOpB = Op3; 950 return true; 951 } 952 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 953 ConstOp->isOne()) { 954 ExtOpA = Op1; 955 ExtOpB = Op2; 956 return true; 957 } 958 return false; 959 }; 960 bool IsCeil = 961 (ExtOpA.getOpcode() == ISD::ADD && 962 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) || 963 (ExtOpB.getOpcode() == ISD::ADD && 964 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA)); 965 966 // If the shift is signed (sra): 967 // - Needs >= 2 sign bit for both operands. 968 // - Needs >= 2 zero bits. 969 // If the shift is unsigned (srl): 970 // - Needs >= 1 zero bit for both operands. 971 // - Needs 1 demanded bit zero and >= 2 sign bits. 972 unsigned ShiftOpc = Op.getOpcode(); 973 bool IsSigned = false; 974 unsigned KnownBits; 975 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 976 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 977 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 978 unsigned NumZeroA = 979 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 980 unsigned NumZeroB = 981 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 982 unsigned NumZero = std::min(NumZeroA, NumZeroB); 983 984 switch (ShiftOpc) { 985 default: 986 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 987 case ISD::SRA: { 988 if (NumZero >= 2 && NumSigned < NumZero) { 989 IsSigned = false; 990 KnownBits = NumZero; 991 break; 992 } 993 if (NumSigned >= 1) { 994 IsSigned = true; 995 KnownBits = NumSigned; 996 break; 997 } 998 return SDValue(); 999 } 1000 case ISD::SRL: { 1001 if (NumZero >= 1 && NumSigned < NumZero) { 1002 IsSigned = false; 1003 KnownBits = NumZero; 1004 break; 1005 } 1006 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1007 IsSigned = true; 1008 KnownBits = NumSigned; 1009 break; 1010 } 1011 return SDValue(); 1012 } 1013 } 1014 1015 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1016 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1017 1018 // Find the smallest power-2 type that is legal for this vector size and 1019 // operation, given the original type size and the number of known sign/zero 1020 // bits. 1021 EVT VT = Op.getValueType(); 1022 unsigned MinWidth = 1023 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1024 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth)); 1025 if (VT.isVector()) 1026 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1027 if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) 1028 return SDValue(); 1029 1030 SDLoc DL(Op); 1031 SDValue ResultAVG = 1032 DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA), 1033 DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB)); 1034 return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT, 1035 ResultAVG); 1036 } 1037 1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1039 /// result of Op are ever used downstream. If we can use this information to 1040 /// simplify Op, create a new simplified DAG node and return true, returning the 1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1042 /// return a mask of Known bits for the expression (used to simplify the 1043 /// caller). The Known bits may only be accurate for those bits in the 1044 /// OriginalDemandedBits and OriginalDemandedElts. 1045 bool TargetLowering::SimplifyDemandedBits( 1046 SDValue Op, const APInt &OriginalDemandedBits, 1047 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1048 unsigned Depth, bool AssumeSingleUse) const { 1049 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1050 assert(Op.getScalarValueSizeInBits() == BitWidth && 1051 "Mask size mismatches value type size!"); 1052 1053 // Don't know anything. 1054 Known = KnownBits(BitWidth); 1055 1056 // TODO: We can probably do more work on calculating the known bits and 1057 // simplifying the operations for scalable vectors, but for now we just 1058 // bail out. 1059 if (Op.getValueType().isScalableVector()) 1060 return false; 1061 1062 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1063 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1064 assert((!Op.getValueType().isVector() || 1065 NumElts == Op.getValueType().getVectorNumElements()) && 1066 "Unexpected vector size"); 1067 1068 APInt DemandedBits = OriginalDemandedBits; 1069 APInt DemandedElts = OriginalDemandedElts; 1070 SDLoc dl(Op); 1071 auto &DL = TLO.DAG.getDataLayout(); 1072 1073 // Undef operand. 1074 if (Op.isUndef()) 1075 return false; 1076 1077 if (Op.getOpcode() == ISD::Constant) { 1078 // We know all of the bits for a constant! 1079 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 1080 return false; 1081 } 1082 1083 if (Op.getOpcode() == ISD::ConstantFP) { 1084 // We know all of the bits for a floating point constant! 1085 Known = KnownBits::makeConstant( 1086 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1087 return false; 1088 } 1089 1090 // Other users may use these bits. 1091 EVT VT = Op.getValueType(); 1092 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 1093 if (Depth != 0) { 1094 // If not at the root, Just compute the Known bits to 1095 // simplify things downstream. 1096 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1097 return false; 1098 } 1099 // If this is the root being simplified, allow it to have multiple uses, 1100 // just set the DemandedBits/Elts to all bits. 1101 DemandedBits = APInt::getAllOnes(BitWidth); 1102 DemandedElts = APInt::getAllOnes(NumElts); 1103 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1104 // Not demanding any bits/elts from Op. 1105 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1106 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1107 // Limit search depth. 1108 return false; 1109 } 1110 1111 KnownBits Known2; 1112 switch (Op.getOpcode()) { 1113 case ISD::TargetConstant: 1114 llvm_unreachable("Can't simplify this node"); 1115 case ISD::SCALAR_TO_VECTOR: { 1116 if (!DemandedElts[0]) 1117 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1118 1119 KnownBits SrcKnown; 1120 SDValue Src = Op.getOperand(0); 1121 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1122 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1123 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1124 return true; 1125 1126 // Upper elements are undef, so only get the knownbits if we just demand 1127 // the bottom element. 1128 if (DemandedElts == 1) 1129 Known = SrcKnown.anyextOrTrunc(BitWidth); 1130 break; 1131 } 1132 case ISD::BUILD_VECTOR: 1133 // Collect the known bits that are shared by every demanded element. 1134 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1135 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1136 return false; // Don't fall through, will infinitely loop. 1137 case ISD::LOAD: { 1138 auto *LD = cast<LoadSDNode>(Op); 1139 if (getTargetConstantFromLoad(LD)) { 1140 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1141 return false; // Don't fall through, will infinitely loop. 1142 } 1143 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1144 // If this is a ZEXTLoad and we are looking at the loaded value. 1145 EVT MemVT = LD->getMemoryVT(); 1146 unsigned MemBits = MemVT.getScalarSizeInBits(); 1147 Known.Zero.setBitsFrom(MemBits); 1148 return false; // Don't fall through, will infinitely loop. 1149 } 1150 break; 1151 } 1152 case ISD::INSERT_VECTOR_ELT: { 1153 SDValue Vec = Op.getOperand(0); 1154 SDValue Scl = Op.getOperand(1); 1155 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1156 EVT VecVT = Vec.getValueType(); 1157 1158 // If index isn't constant, assume we need all vector elements AND the 1159 // inserted element. 1160 APInt DemandedVecElts(DemandedElts); 1161 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1162 unsigned Idx = CIdx->getZExtValue(); 1163 DemandedVecElts.clearBit(Idx); 1164 1165 // Inserted element is not required. 1166 if (!DemandedElts[Idx]) 1167 return TLO.CombineTo(Op, Vec); 1168 } 1169 1170 KnownBits KnownScl; 1171 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1172 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1173 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1174 return true; 1175 1176 Known = KnownScl.anyextOrTrunc(BitWidth); 1177 1178 KnownBits KnownVec; 1179 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1180 Depth + 1)) 1181 return true; 1182 1183 if (!!DemandedVecElts) 1184 Known = KnownBits::commonBits(Known, KnownVec); 1185 1186 return false; 1187 } 1188 case ISD::INSERT_SUBVECTOR: { 1189 // Demand any elements from the subvector and the remainder from the src its 1190 // inserted into. 1191 SDValue Src = Op.getOperand(0); 1192 SDValue Sub = Op.getOperand(1); 1193 uint64_t Idx = Op.getConstantOperandVal(2); 1194 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1195 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1196 APInt DemandedSrcElts = DemandedElts; 1197 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1198 1199 KnownBits KnownSub, KnownSrc; 1200 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1201 Depth + 1)) 1202 return true; 1203 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1204 Depth + 1)) 1205 return true; 1206 1207 Known.Zero.setAllBits(); 1208 Known.One.setAllBits(); 1209 if (!!DemandedSubElts) 1210 Known = KnownBits::commonBits(Known, KnownSub); 1211 if (!!DemandedSrcElts) 1212 Known = KnownBits::commonBits(Known, KnownSrc); 1213 1214 // Attempt to avoid multi-use src if we don't need anything from it. 1215 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1216 !DemandedSrcElts.isAllOnes()) { 1217 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1218 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1219 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1220 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1221 if (NewSub || NewSrc) { 1222 NewSub = NewSub ? NewSub : Sub; 1223 NewSrc = NewSrc ? NewSrc : Src; 1224 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1225 Op.getOperand(2)); 1226 return TLO.CombineTo(Op, NewOp); 1227 } 1228 } 1229 break; 1230 } 1231 case ISD::EXTRACT_SUBVECTOR: { 1232 // Offset the demanded elts by the subvector index. 1233 SDValue Src = Op.getOperand(0); 1234 if (Src.getValueType().isScalableVector()) 1235 break; 1236 uint64_t Idx = Op.getConstantOperandVal(1); 1237 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1238 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1239 1240 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1241 Depth + 1)) 1242 return true; 1243 1244 // Attempt to avoid multi-use src if we don't need anything from it. 1245 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1246 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1247 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1248 if (DemandedSrc) { 1249 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1250 Op.getOperand(1)); 1251 return TLO.CombineTo(Op, NewOp); 1252 } 1253 } 1254 break; 1255 } 1256 case ISD::CONCAT_VECTORS: { 1257 Known.Zero.setAllBits(); 1258 Known.One.setAllBits(); 1259 EVT SubVT = Op.getOperand(0).getValueType(); 1260 unsigned NumSubVecs = Op.getNumOperands(); 1261 unsigned NumSubElts = SubVT.getVectorNumElements(); 1262 for (unsigned i = 0; i != NumSubVecs; ++i) { 1263 APInt DemandedSubElts = 1264 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1265 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1266 Known2, TLO, Depth + 1)) 1267 return true; 1268 // Known bits are shared by every demanded subvector element. 1269 if (!!DemandedSubElts) 1270 Known = KnownBits::commonBits(Known, Known2); 1271 } 1272 break; 1273 } 1274 case ISD::VECTOR_SHUFFLE: { 1275 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1276 1277 // Collect demanded elements from shuffle operands.. 1278 APInt DemandedLHS(NumElts, 0); 1279 APInt DemandedRHS(NumElts, 0); 1280 for (unsigned i = 0; i != NumElts; ++i) { 1281 if (!DemandedElts[i]) 1282 continue; 1283 int M = ShuffleMask[i]; 1284 if (M < 0) { 1285 // For UNDEF elements, we don't know anything about the common state of 1286 // the shuffle result. 1287 DemandedLHS.clearAllBits(); 1288 DemandedRHS.clearAllBits(); 1289 break; 1290 } 1291 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1292 if (M < (int)NumElts) 1293 DemandedLHS.setBit(M); 1294 else 1295 DemandedRHS.setBit(M - NumElts); 1296 } 1297 1298 if (!!DemandedLHS || !!DemandedRHS) { 1299 SDValue Op0 = Op.getOperand(0); 1300 SDValue Op1 = Op.getOperand(1); 1301 1302 Known.Zero.setAllBits(); 1303 Known.One.setAllBits(); 1304 if (!!DemandedLHS) { 1305 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1306 Depth + 1)) 1307 return true; 1308 Known = KnownBits::commonBits(Known, Known2); 1309 } 1310 if (!!DemandedRHS) { 1311 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1312 Depth + 1)) 1313 return true; 1314 Known = KnownBits::commonBits(Known, Known2); 1315 } 1316 1317 // Attempt to avoid multi-use ops if we don't need anything from them. 1318 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1319 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1320 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1321 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1322 if (DemandedOp0 || DemandedOp1) { 1323 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1324 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1325 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1326 return TLO.CombineTo(Op, NewOp); 1327 } 1328 } 1329 break; 1330 } 1331 case ISD::AND: { 1332 SDValue Op0 = Op.getOperand(0); 1333 SDValue Op1 = Op.getOperand(1); 1334 1335 // If the RHS is a constant, check to see if the LHS would be zero without 1336 // using the bits from the RHS. Below, we use knowledge about the RHS to 1337 // simplify the LHS, here we're using information from the LHS to simplify 1338 // the RHS. 1339 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1340 // Do not increment Depth here; that can cause an infinite loop. 1341 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1342 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1343 if ((LHSKnown.Zero & DemandedBits) == 1344 (~RHSC->getAPIntValue() & DemandedBits)) 1345 return TLO.CombineTo(Op, Op0); 1346 1347 // If any of the set bits in the RHS are known zero on the LHS, shrink 1348 // the constant. 1349 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1350 DemandedElts, TLO)) 1351 return true; 1352 1353 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1354 // constant, but if this 'and' is only clearing bits that were just set by 1355 // the xor, then this 'and' can be eliminated by shrinking the mask of 1356 // the xor. For example, for a 32-bit X: 1357 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1358 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1359 LHSKnown.One == ~RHSC->getAPIntValue()) { 1360 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1361 return TLO.CombineTo(Op, Xor); 1362 } 1363 } 1364 1365 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1366 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1367 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && 1368 (Op0.getOperand(0).isUndef() || 1369 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1370 Op0->hasOneUse()) { 1371 unsigned NumSubElts = 1372 Op0.getOperand(1).getValueType().getVectorNumElements(); 1373 unsigned SubIdx = Op0.getConstantOperandVal(2); 1374 APInt DemandedSub = 1375 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1376 KnownBits KnownSubMask = 1377 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1378 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1379 SDValue NewAnd = 1380 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1381 SDValue NewInsert = 1382 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1383 Op0.getOperand(1), Op0.getOperand(2)); 1384 return TLO.CombineTo(Op, NewInsert); 1385 } 1386 } 1387 1388 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1389 Depth + 1)) 1390 return true; 1391 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1392 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1393 Known2, TLO, Depth + 1)) 1394 return true; 1395 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1396 1397 // Attempt to avoid multi-use ops if we don't need anything from them. 1398 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1399 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1400 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1401 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1402 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1403 if (DemandedOp0 || DemandedOp1) { 1404 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1405 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1406 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1407 return TLO.CombineTo(Op, NewOp); 1408 } 1409 } 1410 1411 // If all of the demanded bits are known one on one side, return the other. 1412 // These bits cannot contribute to the result of the 'and'. 1413 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1414 return TLO.CombineTo(Op, Op0); 1415 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1416 return TLO.CombineTo(Op, Op1); 1417 // If all of the demanded bits in the inputs are known zeros, return zero. 1418 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1419 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1420 // If the RHS is a constant, see if we can simplify it. 1421 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1422 TLO)) 1423 return true; 1424 // If the operation can be done in a smaller type, do so. 1425 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1426 return true; 1427 1428 Known &= Known2; 1429 break; 1430 } 1431 case ISD::OR: { 1432 SDValue Op0 = Op.getOperand(0); 1433 SDValue Op1 = Op.getOperand(1); 1434 1435 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1436 Depth + 1)) 1437 return true; 1438 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1439 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1440 Known2, TLO, Depth + 1)) 1441 return true; 1442 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1443 1444 // Attempt to avoid multi-use ops if we don't need anything from them. 1445 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1446 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1447 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1448 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1449 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1450 if (DemandedOp0 || DemandedOp1) { 1451 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1452 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1453 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1454 return TLO.CombineTo(Op, NewOp); 1455 } 1456 } 1457 1458 // If all of the demanded bits are known zero on one side, return the other. 1459 // These bits cannot contribute to the result of the 'or'. 1460 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1461 return TLO.CombineTo(Op, Op0); 1462 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1463 return TLO.CombineTo(Op, Op1); 1464 // If the RHS is a constant, see if we can simplify it. 1465 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1466 return true; 1467 // If the operation can be done in a smaller type, do so. 1468 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1469 return true; 1470 1471 Known |= Known2; 1472 break; 1473 } 1474 case ISD::XOR: { 1475 SDValue Op0 = Op.getOperand(0); 1476 SDValue Op1 = Op.getOperand(1); 1477 1478 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1479 Depth + 1)) 1480 return true; 1481 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1482 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1483 Depth + 1)) 1484 return true; 1485 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1486 1487 // Attempt to avoid multi-use ops if we don't need anything from them. 1488 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1489 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1490 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1491 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1492 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1493 if (DemandedOp0 || DemandedOp1) { 1494 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1495 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1496 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1497 return TLO.CombineTo(Op, NewOp); 1498 } 1499 } 1500 1501 // If all of the demanded bits are known zero on one side, return the other. 1502 // These bits cannot contribute to the result of the 'xor'. 1503 if (DemandedBits.isSubsetOf(Known.Zero)) 1504 return TLO.CombineTo(Op, Op0); 1505 if (DemandedBits.isSubsetOf(Known2.Zero)) 1506 return TLO.CombineTo(Op, Op1); 1507 // If the operation can be done in a smaller type, do so. 1508 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1509 return true; 1510 1511 // If all of the unknown bits are known to be zero on one side or the other 1512 // turn this into an *inclusive* or. 1513 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1514 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1515 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1516 1517 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1518 if (C) { 1519 // If one side is a constant, and all of the set bits in the constant are 1520 // also known set on the other side, turn this into an AND, as we know 1521 // the bits will be cleared. 1522 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1523 // NB: it is okay if more bits are known than are requested 1524 if (C->getAPIntValue() == Known2.One) { 1525 SDValue ANDC = 1526 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1527 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1528 } 1529 1530 // If the RHS is a constant, see if we can change it. Don't alter a -1 1531 // constant because that's a 'not' op, and that is better for combining 1532 // and codegen. 1533 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1534 // We're flipping all demanded bits. Flip the undemanded bits too. 1535 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1536 return TLO.CombineTo(Op, New); 1537 } 1538 } 1539 1540 // If we can't turn this into a 'not', try to shrink the constant. 1541 if (!C || !C->isAllOnes()) 1542 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1543 return true; 1544 1545 Known ^= Known2; 1546 break; 1547 } 1548 case ISD::SELECT: 1549 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1550 Depth + 1)) 1551 return true; 1552 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1553 Depth + 1)) 1554 return true; 1555 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1556 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1557 1558 // If the operands are constants, see if we can simplify them. 1559 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1560 return true; 1561 1562 // Only known if known in both the LHS and RHS. 1563 Known = KnownBits::commonBits(Known, Known2); 1564 break; 1565 case ISD::VSELECT: 1566 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1567 Known, TLO, Depth + 1)) 1568 return true; 1569 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1570 Known2, TLO, Depth + 1)) 1571 return true; 1572 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1573 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1574 1575 // Only known if known in both the LHS and RHS. 1576 Known = KnownBits::commonBits(Known, Known2); 1577 break; 1578 case ISD::SELECT_CC: 1579 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1580 Depth + 1)) 1581 return true; 1582 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1583 Depth + 1)) 1584 return true; 1585 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1586 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1587 1588 // If the operands are constants, see if we can simplify them. 1589 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1590 return true; 1591 1592 // Only known if known in both the LHS and RHS. 1593 Known = KnownBits::commonBits(Known, Known2); 1594 break; 1595 case ISD::SETCC: { 1596 SDValue Op0 = Op.getOperand(0); 1597 SDValue Op1 = Op.getOperand(1); 1598 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1599 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1600 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1601 // -1, we may be able to bypass the setcc. 1602 if (DemandedBits.isSignMask() && 1603 Op0.getScalarValueSizeInBits() == BitWidth && 1604 getBooleanContents(Op0.getValueType()) == 1605 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1606 // If we're testing X < 0, then this compare isn't needed - just use X! 1607 // FIXME: We're limiting to integer types here, but this should also work 1608 // if we don't care about FP signed-zero. The use of SETLT with FP means 1609 // that we don't care about NaNs. 1610 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1611 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1612 return TLO.CombineTo(Op, Op0); 1613 1614 // TODO: Should we check for other forms of sign-bit comparisons? 1615 // Examples: X <= -1, X >= 0 1616 } 1617 if (getBooleanContents(Op0.getValueType()) == 1618 TargetLowering::ZeroOrOneBooleanContent && 1619 BitWidth > 1) 1620 Known.Zero.setBitsFrom(1); 1621 break; 1622 } 1623 case ISD::SHL: { 1624 SDValue Op0 = Op.getOperand(0); 1625 SDValue Op1 = Op.getOperand(1); 1626 EVT ShiftVT = Op1.getValueType(); 1627 1628 if (const APInt *SA = 1629 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1630 unsigned ShAmt = SA->getZExtValue(); 1631 if (ShAmt == 0) 1632 return TLO.CombineTo(Op, Op0); 1633 1634 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1635 // single shift. We can do this if the bottom bits (which are shifted 1636 // out) are never demanded. 1637 // TODO - support non-uniform vector amounts. 1638 if (Op0.getOpcode() == ISD::SRL) { 1639 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1640 if (const APInt *SA2 = 1641 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1642 unsigned C1 = SA2->getZExtValue(); 1643 unsigned Opc = ISD::SHL; 1644 int Diff = ShAmt - C1; 1645 if (Diff < 0) { 1646 Diff = -Diff; 1647 Opc = ISD::SRL; 1648 } 1649 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1650 return TLO.CombineTo( 1651 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1652 } 1653 } 1654 } 1655 1656 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1657 // are not demanded. This will likely allow the anyext to be folded away. 1658 // TODO - support non-uniform vector amounts. 1659 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1660 SDValue InnerOp = Op0.getOperand(0); 1661 EVT InnerVT = InnerOp.getValueType(); 1662 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1663 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1664 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1665 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1666 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1667 ShTy = InnerVT; 1668 SDValue NarrowShl = 1669 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1670 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1671 return TLO.CombineTo( 1672 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1673 } 1674 1675 // Repeat the SHL optimization above in cases where an extension 1676 // intervenes: (shl (anyext (shr x, c1)), c2) to 1677 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1678 // aren't demanded (as above) and that the shifted upper c1 bits of 1679 // x aren't demanded. 1680 // TODO - support non-uniform vector amounts. 1681 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1682 InnerOp.hasOneUse()) { 1683 if (const APInt *SA2 = 1684 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1685 unsigned InnerShAmt = SA2->getZExtValue(); 1686 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1687 DemandedBits.getActiveBits() <= 1688 (InnerBits - InnerShAmt + ShAmt) && 1689 DemandedBits.countTrailingZeros() >= ShAmt) { 1690 SDValue NewSA = 1691 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1692 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1693 InnerOp.getOperand(0)); 1694 return TLO.CombineTo( 1695 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1696 } 1697 } 1698 } 1699 } 1700 1701 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1702 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1703 Depth + 1)) 1704 return true; 1705 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1706 Known.Zero <<= ShAmt; 1707 Known.One <<= ShAmt; 1708 // low bits known zero. 1709 Known.Zero.setLowBits(ShAmt); 1710 1711 // Attempt to avoid multi-use ops if we don't need anything from them. 1712 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1713 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1714 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1715 if (DemandedOp0) { 1716 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1717 return TLO.CombineTo(Op, NewOp); 1718 } 1719 } 1720 1721 // Try shrinking the operation as long as the shift amount will still be 1722 // in range. 1723 if ((ShAmt < DemandedBits.getActiveBits()) && 1724 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1725 return true; 1726 } 1727 1728 // If we are only demanding sign bits then we can use the shift source 1729 // directly. 1730 if (const APInt *MaxSA = 1731 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1732 unsigned ShAmt = MaxSA->getZExtValue(); 1733 unsigned NumSignBits = 1734 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1735 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1736 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1737 return TLO.CombineTo(Op, Op0); 1738 } 1739 break; 1740 } 1741 case ISD::SRL: { 1742 SDValue Op0 = Op.getOperand(0); 1743 SDValue Op1 = Op.getOperand(1); 1744 EVT ShiftVT = Op1.getValueType(); 1745 1746 // Try to match AVG patterns. 1747 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1748 DemandedElts, Depth + 1)) 1749 return TLO.CombineTo(Op, AVG); 1750 1751 if (const APInt *SA = 1752 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1753 unsigned ShAmt = SA->getZExtValue(); 1754 if (ShAmt == 0) 1755 return TLO.CombineTo(Op, Op0); 1756 1757 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1758 // single shift. We can do this if the top bits (which are shifted out) 1759 // are never demanded. 1760 // TODO - support non-uniform vector amounts. 1761 if (Op0.getOpcode() == ISD::SHL) { 1762 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1763 if (const APInt *SA2 = 1764 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1765 unsigned C1 = SA2->getZExtValue(); 1766 unsigned Opc = ISD::SRL; 1767 int Diff = ShAmt - C1; 1768 if (Diff < 0) { 1769 Diff = -Diff; 1770 Opc = ISD::SHL; 1771 } 1772 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1773 return TLO.CombineTo( 1774 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1775 } 1776 } 1777 } 1778 1779 APInt InDemandedMask = (DemandedBits << ShAmt); 1780 1781 // If the shift is exact, then it does demand the low bits (and knows that 1782 // they are zero). 1783 if (Op->getFlags().hasExact()) 1784 InDemandedMask.setLowBits(ShAmt); 1785 1786 // Compute the new bits that are at the top now. 1787 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1788 Depth + 1)) 1789 return true; 1790 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1791 Known.Zero.lshrInPlace(ShAmt); 1792 Known.One.lshrInPlace(ShAmt); 1793 // High bits known zero. 1794 Known.Zero.setHighBits(ShAmt); 1795 } 1796 break; 1797 } 1798 case ISD::SRA: { 1799 SDValue Op0 = Op.getOperand(0); 1800 SDValue Op1 = Op.getOperand(1); 1801 EVT ShiftVT = Op1.getValueType(); 1802 1803 // If we only want bits that already match the signbit then we don't need 1804 // to shift. 1805 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1806 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1807 NumHiDemandedBits) 1808 return TLO.CombineTo(Op, Op0); 1809 1810 // If this is an arithmetic shift right and only the low-bit is set, we can 1811 // always convert this into a logical shr, even if the shift amount is 1812 // variable. The low bit of the shift cannot be an input sign bit unless 1813 // the shift amount is >= the size of the datatype, which is undefined. 1814 if (DemandedBits.isOne()) 1815 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1816 1817 // Try to match AVG patterns. 1818 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1819 DemandedElts, Depth + 1)) 1820 return TLO.CombineTo(Op, AVG); 1821 1822 if (const APInt *SA = 1823 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1824 unsigned ShAmt = SA->getZExtValue(); 1825 if (ShAmt == 0) 1826 return TLO.CombineTo(Op, Op0); 1827 1828 APInt InDemandedMask = (DemandedBits << ShAmt); 1829 1830 // If the shift is exact, then it does demand the low bits (and knows that 1831 // they are zero). 1832 if (Op->getFlags().hasExact()) 1833 InDemandedMask.setLowBits(ShAmt); 1834 1835 // If any of the demanded bits are produced by the sign extension, we also 1836 // demand the input sign bit. 1837 if (DemandedBits.countLeadingZeros() < ShAmt) 1838 InDemandedMask.setSignBit(); 1839 1840 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1841 Depth + 1)) 1842 return true; 1843 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1844 Known.Zero.lshrInPlace(ShAmt); 1845 Known.One.lshrInPlace(ShAmt); 1846 1847 // If the input sign bit is known to be zero, or if none of the top bits 1848 // are demanded, turn this into an unsigned shift right. 1849 if (Known.Zero[BitWidth - ShAmt - 1] || 1850 DemandedBits.countLeadingZeros() >= ShAmt) { 1851 SDNodeFlags Flags; 1852 Flags.setExact(Op->getFlags().hasExact()); 1853 return TLO.CombineTo( 1854 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1855 } 1856 1857 int Log2 = DemandedBits.exactLogBase2(); 1858 if (Log2 >= 0) { 1859 // The bit must come from the sign. 1860 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1861 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1862 } 1863 1864 if (Known.One[BitWidth - ShAmt - 1]) 1865 // New bits are known one. 1866 Known.One.setHighBits(ShAmt); 1867 1868 // Attempt to avoid multi-use ops if we don't need anything from them. 1869 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1870 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1871 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1872 if (DemandedOp0) { 1873 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1874 return TLO.CombineTo(Op, NewOp); 1875 } 1876 } 1877 } 1878 break; 1879 } 1880 case ISD::FSHL: 1881 case ISD::FSHR: { 1882 SDValue Op0 = Op.getOperand(0); 1883 SDValue Op1 = Op.getOperand(1); 1884 SDValue Op2 = Op.getOperand(2); 1885 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1886 1887 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1888 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1889 1890 // For fshl, 0-shift returns the 1st arg. 1891 // For fshr, 0-shift returns the 2nd arg. 1892 if (Amt == 0) { 1893 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1894 Known, TLO, Depth + 1)) 1895 return true; 1896 break; 1897 } 1898 1899 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1900 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1901 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1902 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1903 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1904 Depth + 1)) 1905 return true; 1906 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1907 Depth + 1)) 1908 return true; 1909 1910 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1911 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1912 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1913 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1914 Known.One |= Known2.One; 1915 Known.Zero |= Known2.Zero; 1916 1917 // Attempt to avoid multi-use ops if we don't need anything from them. 1918 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 1919 !DemandedElts.isAllOnes()) { 1920 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1921 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 1922 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1923 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 1924 if (DemandedOp0 || DemandedOp1) { 1925 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 1926 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 1927 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 1928 DemandedOp1, Op2); 1929 return TLO.CombineTo(Op, NewOp); 1930 } 1931 } 1932 } 1933 1934 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1935 if (isPowerOf2_32(BitWidth)) { 1936 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1937 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1938 Known2, TLO, Depth + 1)) 1939 return true; 1940 } 1941 break; 1942 } 1943 case ISD::ROTL: 1944 case ISD::ROTR: { 1945 SDValue Op0 = Op.getOperand(0); 1946 SDValue Op1 = Op.getOperand(1); 1947 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1948 1949 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1950 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1951 return TLO.CombineTo(Op, Op0); 1952 1953 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 1954 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1955 unsigned RevAmt = BitWidth - Amt; 1956 1957 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 1958 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 1959 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 1960 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1961 Depth + 1)) 1962 return true; 1963 1964 // rot*(x, 0) --> x 1965 if (Amt == 0) 1966 return TLO.CombineTo(Op, Op0); 1967 1968 // See if we don't demand either half of the rotated bits. 1969 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 1970 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 1971 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 1972 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 1973 } 1974 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 1975 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 1976 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 1977 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1978 } 1979 } 1980 1981 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1982 if (isPowerOf2_32(BitWidth)) { 1983 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1984 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1985 Depth + 1)) 1986 return true; 1987 } 1988 break; 1989 } 1990 case ISD::UMIN: { 1991 // Check if one arg is always less than (or equal) to the other arg. 1992 SDValue Op0 = Op.getOperand(0); 1993 SDValue Op1 = Op.getOperand(1); 1994 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1995 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1996 Known = KnownBits::umin(Known0, Known1); 1997 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1998 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1999 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2000 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 2001 break; 2002 } 2003 case ISD::UMAX: { 2004 // Check if one arg is always greater than (or equal) to the other arg. 2005 SDValue Op0 = Op.getOperand(0); 2006 SDValue Op1 = Op.getOperand(1); 2007 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2008 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2009 Known = KnownBits::umax(Known0, Known1); 2010 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2011 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 2012 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2013 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 2014 break; 2015 } 2016 case ISD::BITREVERSE: { 2017 SDValue Src = Op.getOperand(0); 2018 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2019 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2020 Depth + 1)) 2021 return true; 2022 Known.One = Known2.One.reverseBits(); 2023 Known.Zero = Known2.Zero.reverseBits(); 2024 break; 2025 } 2026 case ISD::BSWAP: { 2027 SDValue Src = Op.getOperand(0); 2028 2029 // If the only bits demanded come from one byte of the bswap result, 2030 // just shift the input byte into position to eliminate the bswap. 2031 unsigned NLZ = DemandedBits.countLeadingZeros(); 2032 unsigned NTZ = DemandedBits.countTrailingZeros(); 2033 2034 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2035 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2036 // have 14 leading zeros, round to 8. 2037 NLZ = alignDown(NLZ, 8); 2038 NTZ = alignDown(NTZ, 8); 2039 // If we need exactly one byte, we can do this transformation. 2040 if (BitWidth - NLZ - NTZ == 8) { 2041 // Replace this with either a left or right shift to get the byte into 2042 // the right place. 2043 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2044 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2045 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2046 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2047 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2048 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2049 return TLO.CombineTo(Op, NewOp); 2050 } 2051 } 2052 2053 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2054 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2055 Depth + 1)) 2056 return true; 2057 Known.One = Known2.One.byteSwap(); 2058 Known.Zero = Known2.Zero.byteSwap(); 2059 break; 2060 } 2061 case ISD::CTPOP: { 2062 // If only 1 bit is demanded, replace with PARITY as long as we're before 2063 // op legalization. 2064 // FIXME: Limit to scalars for now. 2065 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2066 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2067 Op.getOperand(0))); 2068 2069 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2070 break; 2071 } 2072 case ISD::SIGN_EXTEND_INREG: { 2073 SDValue Op0 = Op.getOperand(0); 2074 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2075 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2076 2077 // If we only care about the highest bit, don't bother shifting right. 2078 if (DemandedBits.isSignMask()) { 2079 unsigned MinSignedBits = 2080 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2081 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2082 // However if the input is already sign extended we expect the sign 2083 // extension to be dropped altogether later and do not simplify. 2084 if (!AlreadySignExtended) { 2085 // Compute the correct shift amount type, which must be getShiftAmountTy 2086 // for scalar types after legalization. 2087 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2088 getShiftAmountTy(VT, DL)); 2089 return TLO.CombineTo(Op, 2090 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2091 } 2092 } 2093 2094 // If none of the extended bits are demanded, eliminate the sextinreg. 2095 if (DemandedBits.getActiveBits() <= ExVTBits) 2096 return TLO.CombineTo(Op, Op0); 2097 2098 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2099 2100 // Since the sign extended bits are demanded, we know that the sign 2101 // bit is demanded. 2102 InputDemandedBits.setBit(ExVTBits - 1); 2103 2104 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2105 Depth + 1)) 2106 return true; 2107 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2108 2109 // If the sign bit of the input is known set or clear, then we know the 2110 // top bits of the result. 2111 2112 // If the input sign bit is known zero, convert this into a zero extension. 2113 if (Known.Zero[ExVTBits - 1]) 2114 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2115 2116 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2117 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2118 Known.One.setBitsFrom(ExVTBits); 2119 Known.Zero &= Mask; 2120 } else { // Input sign bit unknown 2121 Known.Zero &= Mask; 2122 Known.One &= Mask; 2123 } 2124 break; 2125 } 2126 case ISD::BUILD_PAIR: { 2127 EVT HalfVT = Op.getOperand(0).getValueType(); 2128 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2129 2130 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2131 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2132 2133 KnownBits KnownLo, KnownHi; 2134 2135 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2136 return true; 2137 2138 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2139 return true; 2140 2141 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2142 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2143 2144 Known.One = KnownLo.One.zext(BitWidth) | 2145 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2146 break; 2147 } 2148 case ISD::ZERO_EXTEND: 2149 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2150 SDValue Src = Op.getOperand(0); 2151 EVT SrcVT = Src.getValueType(); 2152 unsigned InBits = SrcVT.getScalarSizeInBits(); 2153 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2154 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2155 2156 // If none of the top bits are demanded, convert this into an any_extend. 2157 if (DemandedBits.getActiveBits() <= InBits) { 2158 // If we only need the non-extended bits of the bottom element 2159 // then we can just bitcast to the result. 2160 if (IsLE && IsVecInReg && DemandedElts == 1 && 2161 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2162 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2163 2164 unsigned Opc = 2165 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2166 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2167 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2168 } 2169 2170 APInt InDemandedBits = DemandedBits.trunc(InBits); 2171 APInt InDemandedElts = DemandedElts.zext(InElts); 2172 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2173 Depth + 1)) 2174 return true; 2175 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2176 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2177 Known = Known.zext(BitWidth); 2178 2179 // Attempt to avoid multi-use ops if we don't need anything from them. 2180 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2181 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2182 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2183 break; 2184 } 2185 case ISD::SIGN_EXTEND: 2186 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2187 SDValue Src = Op.getOperand(0); 2188 EVT SrcVT = Src.getValueType(); 2189 unsigned InBits = SrcVT.getScalarSizeInBits(); 2190 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2191 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2192 2193 // If none of the top bits are demanded, convert this into an any_extend. 2194 if (DemandedBits.getActiveBits() <= InBits) { 2195 // If we only need the non-extended bits of the bottom element 2196 // then we can just bitcast to the result. 2197 if (IsLE && IsVecInReg && DemandedElts == 1 && 2198 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2199 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2200 2201 unsigned Opc = 2202 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2203 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2204 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2205 } 2206 2207 APInt InDemandedBits = DemandedBits.trunc(InBits); 2208 APInt InDemandedElts = DemandedElts.zext(InElts); 2209 2210 // Since some of the sign extended bits are demanded, we know that the sign 2211 // bit is demanded. 2212 InDemandedBits.setBit(InBits - 1); 2213 2214 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2215 Depth + 1)) 2216 return true; 2217 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2218 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2219 2220 // If the sign bit is known one, the top bits match. 2221 Known = Known.sext(BitWidth); 2222 2223 // If the sign bit is known zero, convert this to a zero extend. 2224 if (Known.isNonNegative()) { 2225 unsigned Opc = 2226 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2227 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2228 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2229 } 2230 2231 // Attempt to avoid multi-use ops if we don't need anything from them. 2232 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2233 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2234 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2235 break; 2236 } 2237 case ISD::ANY_EXTEND: 2238 case ISD::ANY_EXTEND_VECTOR_INREG: { 2239 SDValue Src = Op.getOperand(0); 2240 EVT SrcVT = Src.getValueType(); 2241 unsigned InBits = SrcVT.getScalarSizeInBits(); 2242 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2243 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2244 2245 // If we only need the bottom element then we can just bitcast. 2246 // TODO: Handle ANY_EXTEND? 2247 if (IsLE && IsVecInReg && DemandedElts == 1 && 2248 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2249 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2250 2251 APInt InDemandedBits = DemandedBits.trunc(InBits); 2252 APInt InDemandedElts = DemandedElts.zext(InElts); 2253 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2254 Depth + 1)) 2255 return true; 2256 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2257 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2258 Known = Known.anyext(BitWidth); 2259 2260 // Attempt to avoid multi-use ops if we don't need anything from them. 2261 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2262 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2263 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2264 break; 2265 } 2266 case ISD::TRUNCATE: { 2267 SDValue Src = Op.getOperand(0); 2268 2269 // Simplify the input, using demanded bit information, and compute the known 2270 // zero/one bits live out. 2271 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2272 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2273 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2274 Depth + 1)) 2275 return true; 2276 Known = Known.trunc(BitWidth); 2277 2278 // Attempt to avoid multi-use ops if we don't need anything from them. 2279 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2280 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2281 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2282 2283 // If the input is only used by this truncate, see if we can shrink it based 2284 // on the known demanded bits. 2285 if (Src.getNode()->hasOneUse()) { 2286 switch (Src.getOpcode()) { 2287 default: 2288 break; 2289 case ISD::SRL: 2290 // Shrink SRL by a constant if none of the high bits shifted in are 2291 // demanded. 2292 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2293 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2294 // undesirable. 2295 break; 2296 2297 const APInt *ShAmtC = 2298 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2299 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2300 break; 2301 uint64_t ShVal = ShAmtC->getZExtValue(); 2302 2303 APInt HighBits = 2304 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2305 HighBits.lshrInPlace(ShVal); 2306 HighBits = HighBits.trunc(BitWidth); 2307 2308 if (!(HighBits & DemandedBits)) { 2309 // None of the shifted in bits are needed. Add a truncate of the 2310 // shift input, then shift it. 2311 SDValue NewShAmt = TLO.DAG.getConstant( 2312 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2313 SDValue NewTrunc = 2314 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2315 return TLO.CombineTo( 2316 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2317 } 2318 break; 2319 } 2320 } 2321 2322 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2323 break; 2324 } 2325 case ISD::AssertZext: { 2326 // AssertZext demands all of the high bits, plus any of the low bits 2327 // demanded by its users. 2328 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2329 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2330 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2331 TLO, Depth + 1)) 2332 return true; 2333 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2334 2335 Known.Zero |= ~InMask; 2336 break; 2337 } 2338 case ISD::EXTRACT_VECTOR_ELT: { 2339 SDValue Src = Op.getOperand(0); 2340 SDValue Idx = Op.getOperand(1); 2341 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2342 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2343 2344 if (SrcEltCnt.isScalable()) 2345 return false; 2346 2347 // Demand the bits from every vector element without a constant index. 2348 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2349 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2350 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2351 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2352 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2353 2354 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2355 // anything about the extended bits. 2356 APInt DemandedSrcBits = DemandedBits; 2357 if (BitWidth > EltBitWidth) 2358 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2359 2360 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2361 Depth + 1)) 2362 return true; 2363 2364 // Attempt to avoid multi-use ops if we don't need anything from them. 2365 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2366 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2367 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2368 SDValue NewOp = 2369 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2370 return TLO.CombineTo(Op, NewOp); 2371 } 2372 } 2373 2374 Known = Known2; 2375 if (BitWidth > EltBitWidth) 2376 Known = Known.anyext(BitWidth); 2377 break; 2378 } 2379 case ISD::BITCAST: { 2380 SDValue Src = Op.getOperand(0); 2381 EVT SrcVT = Src.getValueType(); 2382 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2383 2384 // If this is an FP->Int bitcast and if the sign bit is the only 2385 // thing demanded, turn this into a FGETSIGN. 2386 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2387 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2388 SrcVT.isFloatingPoint()) { 2389 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2390 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2391 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2392 SrcVT != MVT::f128) { 2393 // Cannot eliminate/lower SHL for f128 yet. 2394 EVT Ty = OpVTLegal ? VT : MVT::i32; 2395 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2396 // place. We expect the SHL to be eliminated by other optimizations. 2397 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2398 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2399 if (!OpVTLegal && OpVTSizeInBits > 32) 2400 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2401 unsigned ShVal = Op.getValueSizeInBits() - 1; 2402 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2403 return TLO.CombineTo(Op, 2404 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2405 } 2406 } 2407 2408 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2409 // Demand the elt/bit if any of the original elts/bits are demanded. 2410 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2411 unsigned Scale = BitWidth / NumSrcEltBits; 2412 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2413 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2414 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2415 for (unsigned i = 0; i != Scale; ++i) { 2416 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2417 unsigned BitOffset = EltOffset * NumSrcEltBits; 2418 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2419 if (!Sub.isZero()) { 2420 DemandedSrcBits |= Sub; 2421 for (unsigned j = 0; j != NumElts; ++j) 2422 if (DemandedElts[j]) 2423 DemandedSrcElts.setBit((j * Scale) + i); 2424 } 2425 } 2426 2427 APInt KnownSrcUndef, KnownSrcZero; 2428 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2429 KnownSrcZero, TLO, Depth + 1)) 2430 return true; 2431 2432 KnownBits KnownSrcBits; 2433 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2434 KnownSrcBits, TLO, Depth + 1)) 2435 return true; 2436 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2437 // TODO - bigendian once we have test coverage. 2438 unsigned Scale = NumSrcEltBits / BitWidth; 2439 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2440 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2441 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2442 for (unsigned i = 0; i != NumElts; ++i) 2443 if (DemandedElts[i]) { 2444 unsigned Offset = (i % Scale) * BitWidth; 2445 DemandedSrcBits.insertBits(DemandedBits, Offset); 2446 DemandedSrcElts.setBit(i / Scale); 2447 } 2448 2449 if (SrcVT.isVector()) { 2450 APInt KnownSrcUndef, KnownSrcZero; 2451 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2452 KnownSrcZero, TLO, Depth + 1)) 2453 return true; 2454 } 2455 2456 KnownBits KnownSrcBits; 2457 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2458 KnownSrcBits, TLO, Depth + 1)) 2459 return true; 2460 } 2461 2462 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2463 // recursive call where Known may be useful to the caller. 2464 if (Depth > 0) { 2465 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2466 return false; 2467 } 2468 break; 2469 } 2470 case ISD::MUL: 2471 if (DemandedBits.isPowerOf2()) { 2472 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2473 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2474 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2475 unsigned CTZ = DemandedBits.countTrailingZeros(); 2476 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2477 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2478 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2479 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2480 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2481 return TLO.CombineTo(Op, Shl); 2482 } 2483 } 2484 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2485 // X * X is odd iff X is odd. 2486 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2487 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2488 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2489 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2490 return TLO.CombineTo(Op, And1); 2491 } 2492 LLVM_FALLTHROUGH; 2493 case ISD::ADD: 2494 case ISD::SUB: { 2495 // Add, Sub, and Mul don't demand any bits in positions beyond that 2496 // of the highest bit demanded of them. 2497 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2498 SDNodeFlags Flags = Op.getNode()->getFlags(); 2499 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2500 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2501 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2502 Depth + 1) || 2503 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2504 Depth + 1) || 2505 // See if the operation should be performed at a smaller bit width. 2506 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2507 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2508 // Disable the nsw and nuw flags. We can no longer guarantee that we 2509 // won't wrap after simplification. 2510 Flags.setNoSignedWrap(false); 2511 Flags.setNoUnsignedWrap(false); 2512 Op->setFlags(Flags); 2513 } 2514 return true; 2515 } 2516 2517 // Attempt to avoid multi-use ops if we don't need anything from them. 2518 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2519 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2520 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2521 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2522 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2523 if (DemandedOp0 || DemandedOp1) { 2524 Flags.setNoSignedWrap(false); 2525 Flags.setNoUnsignedWrap(false); 2526 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2527 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2528 SDValue NewOp = 2529 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2530 return TLO.CombineTo(Op, NewOp); 2531 } 2532 } 2533 2534 // If we have a constant operand, we may be able to turn it into -1 if we 2535 // do not demand the high bits. This can make the constant smaller to 2536 // encode, allow more general folding, or match specialized instruction 2537 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2538 // is probably not useful (and could be detrimental). 2539 ConstantSDNode *C = isConstOrConstSplat(Op1); 2540 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2541 if (C && !C->isAllOnes() && !C->isOne() && 2542 (C->getAPIntValue() | HighMask).isAllOnes()) { 2543 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2544 // Disable the nsw and nuw flags. We can no longer guarantee that we 2545 // won't wrap after simplification. 2546 Flags.setNoSignedWrap(false); 2547 Flags.setNoUnsignedWrap(false); 2548 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2549 return TLO.CombineTo(Op, NewOp); 2550 } 2551 2552 // Match a multiply with a disguised negated-power-of-2 and convert to a 2553 // an equivalent shift-left amount. 2554 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2555 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2556 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2557 return 0; 2558 2559 // Don't touch opaque constants. Also, ignore zero and power-of-2 2560 // multiplies. Those will get folded later. 2561 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2562 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2563 !MulC->getAPIntValue().isPowerOf2()) { 2564 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2565 if (UnmaskedC.isNegatedPowerOf2()) 2566 return (-UnmaskedC).logBase2(); 2567 } 2568 return 0; 2569 }; 2570 2571 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) { 2572 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2573 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2574 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2575 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2576 return TLO.CombineTo(Op, Res); 2577 }; 2578 2579 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2580 if (Op.getOpcode() == ISD::ADD) { 2581 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2582 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2583 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2584 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2585 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2586 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2587 } 2588 if (Op.getOpcode() == ISD::SUB) { 2589 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2590 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2591 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2592 } 2593 } 2594 2595 LLVM_FALLTHROUGH; 2596 } 2597 default: 2598 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2599 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2600 Known, TLO, Depth)) 2601 return true; 2602 break; 2603 } 2604 2605 // Just use computeKnownBits to compute output bits. 2606 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2607 break; 2608 } 2609 2610 // If we know the value of all of the demanded bits, return this as a 2611 // constant. 2612 if (!isTargetCanonicalConstantNode(Op) && 2613 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2614 // Avoid folding to a constant if any OpaqueConstant is involved. 2615 const SDNode *N = Op.getNode(); 2616 for (SDNode *Op : 2617 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2618 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2619 if (C->isOpaque()) 2620 return false; 2621 } 2622 if (VT.isInteger()) 2623 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2624 if (VT.isFloatingPoint()) 2625 return TLO.CombineTo( 2626 Op, 2627 TLO.DAG.getConstantFP( 2628 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2629 } 2630 2631 return false; 2632 } 2633 2634 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2635 const APInt &DemandedElts, 2636 DAGCombinerInfo &DCI) const { 2637 SelectionDAG &DAG = DCI.DAG; 2638 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2639 !DCI.isBeforeLegalizeOps()); 2640 2641 APInt KnownUndef, KnownZero; 2642 bool Simplified = 2643 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2644 if (Simplified) { 2645 DCI.AddToWorklist(Op.getNode()); 2646 DCI.CommitTargetLoweringOpt(TLO); 2647 } 2648 2649 return Simplified; 2650 } 2651 2652 /// Given a vector binary operation and known undefined elements for each input 2653 /// operand, compute whether each element of the output is undefined. 2654 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2655 const APInt &UndefOp0, 2656 const APInt &UndefOp1) { 2657 EVT VT = BO.getValueType(); 2658 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2659 "Vector binop only"); 2660 2661 EVT EltVT = VT.getVectorElementType(); 2662 unsigned NumElts = VT.getVectorNumElements(); 2663 assert(UndefOp0.getBitWidth() == NumElts && 2664 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2665 2666 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2667 const APInt &UndefVals) { 2668 if (UndefVals[Index]) 2669 return DAG.getUNDEF(EltVT); 2670 2671 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2672 // Try hard to make sure that the getNode() call is not creating temporary 2673 // nodes. Ignore opaque integers because they do not constant fold. 2674 SDValue Elt = BV->getOperand(Index); 2675 auto *C = dyn_cast<ConstantSDNode>(Elt); 2676 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2677 return Elt; 2678 } 2679 2680 return SDValue(); 2681 }; 2682 2683 APInt KnownUndef = APInt::getZero(NumElts); 2684 for (unsigned i = 0; i != NumElts; ++i) { 2685 // If both inputs for this element are either constant or undef and match 2686 // the element type, compute the constant/undef result for this element of 2687 // the vector. 2688 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2689 // not handle FP constants. The code within getNode() should be refactored 2690 // to avoid the danger of creating a bogus temporary node here. 2691 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2692 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2693 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2694 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2695 KnownUndef.setBit(i); 2696 } 2697 return KnownUndef; 2698 } 2699 2700 bool TargetLowering::SimplifyDemandedVectorElts( 2701 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2702 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2703 bool AssumeSingleUse) const { 2704 EVT VT = Op.getValueType(); 2705 unsigned Opcode = Op.getOpcode(); 2706 APInt DemandedElts = OriginalDemandedElts; 2707 unsigned NumElts = DemandedElts.getBitWidth(); 2708 assert(VT.isVector() && "Expected vector op"); 2709 2710 KnownUndef = KnownZero = APInt::getZero(NumElts); 2711 2712 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2713 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2714 return false; 2715 2716 // TODO: For now we assume we know nothing about scalable vectors. 2717 if (VT.isScalableVector()) 2718 return false; 2719 2720 assert(VT.getVectorNumElements() == NumElts && 2721 "Mask size mismatches value type element count!"); 2722 2723 // Undef operand. 2724 if (Op.isUndef()) { 2725 KnownUndef.setAllBits(); 2726 return false; 2727 } 2728 2729 // If Op has other users, assume that all elements are needed. 2730 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2731 DemandedElts.setAllBits(); 2732 2733 // Not demanding any elements from Op. 2734 if (DemandedElts == 0) { 2735 KnownUndef.setAllBits(); 2736 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2737 } 2738 2739 // Limit search depth. 2740 if (Depth >= SelectionDAG::MaxRecursionDepth) 2741 return false; 2742 2743 SDLoc DL(Op); 2744 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2745 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2746 2747 // Helper for demanding the specified elements and all the bits of both binary 2748 // operands. 2749 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2750 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2751 TLO.DAG, Depth + 1); 2752 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2753 TLO.DAG, Depth + 1); 2754 if (NewOp0 || NewOp1) { 2755 SDValue NewOp = TLO.DAG.getNode( 2756 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2757 return TLO.CombineTo(Op, NewOp); 2758 } 2759 return false; 2760 }; 2761 2762 switch (Opcode) { 2763 case ISD::SCALAR_TO_VECTOR: { 2764 if (!DemandedElts[0]) { 2765 KnownUndef.setAllBits(); 2766 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2767 } 2768 SDValue ScalarSrc = Op.getOperand(0); 2769 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2770 SDValue Src = ScalarSrc.getOperand(0); 2771 SDValue Idx = ScalarSrc.getOperand(1); 2772 EVT SrcVT = Src.getValueType(); 2773 2774 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2775 2776 if (SrcEltCnt.isScalable()) 2777 return false; 2778 2779 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2780 if (isNullConstant(Idx)) { 2781 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2782 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2783 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2784 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2785 TLO, Depth + 1)) 2786 return true; 2787 } 2788 } 2789 KnownUndef.setHighBits(NumElts - 1); 2790 break; 2791 } 2792 case ISD::BITCAST: { 2793 SDValue Src = Op.getOperand(0); 2794 EVT SrcVT = Src.getValueType(); 2795 2796 // We only handle vectors here. 2797 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2798 if (!SrcVT.isVector()) 2799 break; 2800 2801 // Fast handling of 'identity' bitcasts. 2802 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2803 if (NumSrcElts == NumElts) 2804 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2805 KnownZero, TLO, Depth + 1); 2806 2807 APInt SrcDemandedElts, SrcZero, SrcUndef; 2808 2809 // Bitcast from 'large element' src vector to 'small element' vector, we 2810 // must demand a source element if any DemandedElt maps to it. 2811 if ((NumElts % NumSrcElts) == 0) { 2812 unsigned Scale = NumElts / NumSrcElts; 2813 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2814 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2815 TLO, Depth + 1)) 2816 return true; 2817 2818 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2819 // of the large element. 2820 // TODO - bigendian once we have test coverage. 2821 if (IsLE) { 2822 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2823 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2824 for (unsigned i = 0; i != NumElts; ++i) 2825 if (DemandedElts[i]) { 2826 unsigned Ofs = (i % Scale) * EltSizeInBits; 2827 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2828 } 2829 2830 KnownBits Known; 2831 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2832 TLO, Depth + 1)) 2833 return true; 2834 2835 // The bitcast has split each wide element into a number of 2836 // narrow subelements. We have just computed the Known bits 2837 // for wide elements. See if element splitting results in 2838 // some subelements being zero. Only for demanded elements! 2839 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2840 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2841 .isAllOnes()) 2842 continue; 2843 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2844 unsigned Elt = Scale * SrcElt + SubElt; 2845 if (DemandedElts[Elt]) 2846 KnownZero.setBit(Elt); 2847 } 2848 } 2849 } 2850 2851 // If the src element is zero/undef then all the output elements will be - 2852 // only demanded elements are guaranteed to be correct. 2853 for (unsigned i = 0; i != NumSrcElts; ++i) { 2854 if (SrcDemandedElts[i]) { 2855 if (SrcZero[i]) 2856 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2857 if (SrcUndef[i]) 2858 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2859 } 2860 } 2861 } 2862 2863 // Bitcast from 'small element' src vector to 'large element' vector, we 2864 // demand all smaller source elements covered by the larger demanded element 2865 // of this vector. 2866 if ((NumSrcElts % NumElts) == 0) { 2867 unsigned Scale = NumSrcElts / NumElts; 2868 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2869 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2870 TLO, Depth + 1)) 2871 return true; 2872 2873 // If all the src elements covering an output element are zero/undef, then 2874 // the output element will be as well, assuming it was demanded. 2875 for (unsigned i = 0; i != NumElts; ++i) { 2876 if (DemandedElts[i]) { 2877 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2878 KnownZero.setBit(i); 2879 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2880 KnownUndef.setBit(i); 2881 } 2882 } 2883 } 2884 break; 2885 } 2886 case ISD::BUILD_VECTOR: { 2887 // Check all elements and simplify any unused elements with UNDEF. 2888 if (!DemandedElts.isAllOnes()) { 2889 // Don't simplify BROADCASTS. 2890 if (llvm::any_of(Op->op_values(), 2891 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2892 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2893 bool Updated = false; 2894 for (unsigned i = 0; i != NumElts; ++i) { 2895 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2896 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2897 KnownUndef.setBit(i); 2898 Updated = true; 2899 } 2900 } 2901 if (Updated) 2902 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2903 } 2904 } 2905 for (unsigned i = 0; i != NumElts; ++i) { 2906 SDValue SrcOp = Op.getOperand(i); 2907 if (SrcOp.isUndef()) { 2908 KnownUndef.setBit(i); 2909 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2910 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2911 KnownZero.setBit(i); 2912 } 2913 } 2914 break; 2915 } 2916 case ISD::CONCAT_VECTORS: { 2917 EVT SubVT = Op.getOperand(0).getValueType(); 2918 unsigned NumSubVecs = Op.getNumOperands(); 2919 unsigned NumSubElts = SubVT.getVectorNumElements(); 2920 for (unsigned i = 0; i != NumSubVecs; ++i) { 2921 SDValue SubOp = Op.getOperand(i); 2922 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2923 APInt SubUndef, SubZero; 2924 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2925 Depth + 1)) 2926 return true; 2927 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2928 KnownZero.insertBits(SubZero, i * NumSubElts); 2929 } 2930 2931 // Attempt to avoid multi-use ops if we don't need anything from them. 2932 if (!DemandedElts.isAllOnes()) { 2933 bool FoundNewSub = false; 2934 SmallVector<SDValue, 2> DemandedSubOps; 2935 for (unsigned i = 0; i != NumSubVecs; ++i) { 2936 SDValue SubOp = Op.getOperand(i); 2937 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2938 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 2939 SubOp, SubElts, TLO.DAG, Depth + 1); 2940 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 2941 FoundNewSub = NewSubOp ? true : FoundNewSub; 2942 } 2943 if (FoundNewSub) { 2944 SDValue NewOp = 2945 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 2946 return TLO.CombineTo(Op, NewOp); 2947 } 2948 } 2949 break; 2950 } 2951 case ISD::INSERT_SUBVECTOR: { 2952 // Demand any elements from the subvector and the remainder from the src its 2953 // inserted into. 2954 SDValue Src = Op.getOperand(0); 2955 SDValue Sub = Op.getOperand(1); 2956 uint64_t Idx = Op.getConstantOperandVal(2); 2957 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2958 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2959 APInt DemandedSrcElts = DemandedElts; 2960 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2961 2962 APInt SubUndef, SubZero; 2963 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2964 Depth + 1)) 2965 return true; 2966 2967 // If none of the src operand elements are demanded, replace it with undef. 2968 if (!DemandedSrcElts && !Src.isUndef()) 2969 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2970 TLO.DAG.getUNDEF(VT), Sub, 2971 Op.getOperand(2))); 2972 2973 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2974 TLO, Depth + 1)) 2975 return true; 2976 KnownUndef.insertBits(SubUndef, Idx); 2977 KnownZero.insertBits(SubZero, Idx); 2978 2979 // Attempt to avoid multi-use ops if we don't need anything from them. 2980 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 2981 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2982 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2983 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2984 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2985 if (NewSrc || NewSub) { 2986 NewSrc = NewSrc ? NewSrc : Src; 2987 NewSub = NewSub ? NewSub : Sub; 2988 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2989 NewSub, Op.getOperand(2)); 2990 return TLO.CombineTo(Op, NewOp); 2991 } 2992 } 2993 break; 2994 } 2995 case ISD::EXTRACT_SUBVECTOR: { 2996 // Offset the demanded elts by the subvector index. 2997 SDValue Src = Op.getOperand(0); 2998 if (Src.getValueType().isScalableVector()) 2999 break; 3000 uint64_t Idx = Op.getConstantOperandVal(1); 3001 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3002 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3003 3004 APInt SrcUndef, SrcZero; 3005 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3006 Depth + 1)) 3007 return true; 3008 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3009 KnownZero = SrcZero.extractBits(NumElts, Idx); 3010 3011 // Attempt to avoid multi-use ops if we don't need anything from them. 3012 if (!DemandedElts.isAllOnes()) { 3013 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3014 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3015 if (NewSrc) { 3016 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3017 Op.getOperand(1)); 3018 return TLO.CombineTo(Op, NewOp); 3019 } 3020 } 3021 break; 3022 } 3023 case ISD::INSERT_VECTOR_ELT: { 3024 SDValue Vec = Op.getOperand(0); 3025 SDValue Scl = Op.getOperand(1); 3026 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3027 3028 // For a legal, constant insertion index, if we don't need this insertion 3029 // then strip it, else remove it from the demanded elts. 3030 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3031 unsigned Idx = CIdx->getZExtValue(); 3032 if (!DemandedElts[Idx]) 3033 return TLO.CombineTo(Op, Vec); 3034 3035 APInt DemandedVecElts(DemandedElts); 3036 DemandedVecElts.clearBit(Idx); 3037 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3038 KnownZero, TLO, Depth + 1)) 3039 return true; 3040 3041 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3042 3043 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3044 break; 3045 } 3046 3047 APInt VecUndef, VecZero; 3048 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3049 Depth + 1)) 3050 return true; 3051 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3052 break; 3053 } 3054 case ISD::VSELECT: { 3055 // Try to transform the select condition based on the current demanded 3056 // elements. 3057 // TODO: If a condition element is undef, we can choose from one arm of the 3058 // select (and if one arm is undef, then we can propagate that to the 3059 // result). 3060 // TODO - add support for constant vselect masks (see IR version of this). 3061 APInt UnusedUndef, UnusedZero; 3062 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 3063 UnusedZero, TLO, Depth + 1)) 3064 return true; 3065 3066 // See if we can simplify either vselect operand. 3067 APInt DemandedLHS(DemandedElts); 3068 APInt DemandedRHS(DemandedElts); 3069 APInt UndefLHS, ZeroLHS; 3070 APInt UndefRHS, ZeroRHS; 3071 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 3072 ZeroLHS, TLO, Depth + 1)) 3073 return true; 3074 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 3075 ZeroRHS, TLO, Depth + 1)) 3076 return true; 3077 3078 KnownUndef = UndefLHS & UndefRHS; 3079 KnownZero = ZeroLHS & ZeroRHS; 3080 break; 3081 } 3082 case ISD::VECTOR_SHUFFLE: { 3083 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3084 3085 // Collect demanded elements from shuffle operands.. 3086 APInt DemandedLHS(NumElts, 0); 3087 APInt DemandedRHS(NumElts, 0); 3088 for (unsigned i = 0; i != NumElts; ++i) { 3089 int M = ShuffleMask[i]; 3090 if (M < 0 || !DemandedElts[i]) 3091 continue; 3092 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3093 if (M < (int)NumElts) 3094 DemandedLHS.setBit(M); 3095 else 3096 DemandedRHS.setBit(M - NumElts); 3097 } 3098 3099 // See if we can simplify either shuffle operand. 3100 APInt UndefLHS, ZeroLHS; 3101 APInt UndefRHS, ZeroRHS; 3102 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3103 ZeroLHS, TLO, Depth + 1)) 3104 return true; 3105 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3106 ZeroRHS, TLO, Depth + 1)) 3107 return true; 3108 3109 // Simplify mask using undef elements from LHS/RHS. 3110 bool Updated = false; 3111 bool IdentityLHS = true, IdentityRHS = true; 3112 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3113 for (unsigned i = 0; i != NumElts; ++i) { 3114 int &M = NewMask[i]; 3115 if (M < 0) 3116 continue; 3117 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3118 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3119 Updated = true; 3120 M = -1; 3121 } 3122 IdentityLHS &= (M < 0) || (M == (int)i); 3123 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3124 } 3125 3126 // Update legal shuffle masks based on demanded elements if it won't reduce 3127 // to Identity which can cause premature removal of the shuffle mask. 3128 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3129 SDValue LegalShuffle = 3130 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3131 NewMask, TLO.DAG); 3132 if (LegalShuffle) 3133 return TLO.CombineTo(Op, LegalShuffle); 3134 } 3135 3136 // Propagate undef/zero elements from LHS/RHS. 3137 for (unsigned i = 0; i != NumElts; ++i) { 3138 int M = ShuffleMask[i]; 3139 if (M < 0) { 3140 KnownUndef.setBit(i); 3141 } else if (M < (int)NumElts) { 3142 if (UndefLHS[M]) 3143 KnownUndef.setBit(i); 3144 if (ZeroLHS[M]) 3145 KnownZero.setBit(i); 3146 } else { 3147 if (UndefRHS[M - NumElts]) 3148 KnownUndef.setBit(i); 3149 if (ZeroRHS[M - NumElts]) 3150 KnownZero.setBit(i); 3151 } 3152 } 3153 break; 3154 } 3155 case ISD::ANY_EXTEND_VECTOR_INREG: 3156 case ISD::SIGN_EXTEND_VECTOR_INREG: 3157 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3158 APInt SrcUndef, SrcZero; 3159 SDValue Src = Op.getOperand(0); 3160 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3161 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3162 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3163 Depth + 1)) 3164 return true; 3165 KnownZero = SrcZero.zextOrTrunc(NumElts); 3166 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3167 3168 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3169 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3170 DemandedSrcElts == 1) { 3171 // aext - if we just need the bottom element then we can bitcast. 3172 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3173 } 3174 3175 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3176 // zext(undef) upper bits are guaranteed to be zero. 3177 if (DemandedElts.isSubsetOf(KnownUndef)) 3178 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3179 KnownUndef.clearAllBits(); 3180 3181 // zext - if we just need the bottom element then we can mask: 3182 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3183 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3184 Op->isOnlyUserOf(Src.getNode()) && 3185 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3186 SDLoc DL(Op); 3187 EVT SrcVT = Src.getValueType(); 3188 EVT SrcSVT = SrcVT.getScalarType(); 3189 SmallVector<SDValue> MaskElts; 3190 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3191 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3192 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3193 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3194 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3195 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3196 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3197 } 3198 } 3199 } 3200 break; 3201 } 3202 3203 // TODO: There are more binop opcodes that could be handled here - MIN, 3204 // MAX, saturated math, etc. 3205 case ISD::ADD: { 3206 SDValue Op0 = Op.getOperand(0); 3207 SDValue Op1 = Op.getOperand(1); 3208 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3209 APInt UndefLHS, ZeroLHS; 3210 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3211 Depth + 1, /*AssumeSingleUse*/ true)) 3212 return true; 3213 } 3214 LLVM_FALLTHROUGH; 3215 } 3216 case ISD::OR: 3217 case ISD::XOR: 3218 case ISD::SUB: 3219 case ISD::FADD: 3220 case ISD::FSUB: 3221 case ISD::FMUL: 3222 case ISD::FDIV: 3223 case ISD::FREM: { 3224 SDValue Op0 = Op.getOperand(0); 3225 SDValue Op1 = Op.getOperand(1); 3226 3227 APInt UndefRHS, ZeroRHS; 3228 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3229 Depth + 1)) 3230 return true; 3231 APInt UndefLHS, ZeroLHS; 3232 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3233 Depth + 1)) 3234 return true; 3235 3236 KnownZero = ZeroLHS & ZeroRHS; 3237 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3238 3239 // Attempt to avoid multi-use ops if we don't need anything from them. 3240 // TODO - use KnownUndef to relax the demandedelts? 3241 if (!DemandedElts.isAllOnes()) 3242 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3243 return true; 3244 break; 3245 } 3246 case ISD::SHL: 3247 case ISD::SRL: 3248 case ISD::SRA: 3249 case ISD::ROTL: 3250 case ISD::ROTR: { 3251 SDValue Op0 = Op.getOperand(0); 3252 SDValue Op1 = Op.getOperand(1); 3253 3254 APInt UndefRHS, ZeroRHS; 3255 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3256 Depth + 1)) 3257 return true; 3258 APInt UndefLHS, ZeroLHS; 3259 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3260 Depth + 1)) 3261 return true; 3262 3263 KnownZero = ZeroLHS; 3264 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3265 3266 // Attempt to avoid multi-use ops if we don't need anything from them. 3267 // TODO - use KnownUndef to relax the demandedelts? 3268 if (!DemandedElts.isAllOnes()) 3269 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3270 return true; 3271 break; 3272 } 3273 case ISD::MUL: 3274 case ISD::AND: { 3275 SDValue Op0 = Op.getOperand(0); 3276 SDValue Op1 = Op.getOperand(1); 3277 3278 APInt SrcUndef, SrcZero; 3279 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3280 Depth + 1)) 3281 return true; 3282 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3283 TLO, Depth + 1)) 3284 return true; 3285 3286 // If either side has a zero element, then the result element is zero, even 3287 // if the other is an UNDEF. 3288 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3289 // and then handle 'and' nodes with the rest of the binop opcodes. 3290 KnownZero |= SrcZero; 3291 KnownUndef &= SrcUndef; 3292 KnownUndef &= ~KnownZero; 3293 3294 // Attempt to avoid multi-use ops if we don't need anything from them. 3295 // TODO - use KnownUndef to relax the demandedelts? 3296 if (!DemandedElts.isAllOnes()) 3297 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3298 return true; 3299 break; 3300 } 3301 case ISD::TRUNCATE: 3302 case ISD::SIGN_EXTEND: 3303 case ISD::ZERO_EXTEND: 3304 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3305 KnownZero, TLO, Depth + 1)) 3306 return true; 3307 3308 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3309 // zext(undef) upper bits are guaranteed to be zero. 3310 if (DemandedElts.isSubsetOf(KnownUndef)) 3311 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3312 KnownUndef.clearAllBits(); 3313 } 3314 break; 3315 default: { 3316 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3317 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3318 KnownZero, TLO, Depth)) 3319 return true; 3320 } else { 3321 KnownBits Known; 3322 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3323 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3324 TLO, Depth, AssumeSingleUse)) 3325 return true; 3326 } 3327 break; 3328 } 3329 } 3330 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3331 3332 // Constant fold all undef cases. 3333 // TODO: Handle zero cases as well. 3334 if (DemandedElts.isSubsetOf(KnownUndef)) 3335 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3336 3337 return false; 3338 } 3339 3340 /// Determine which of the bits specified in Mask are known to be either zero or 3341 /// one and return them in the Known. 3342 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3343 KnownBits &Known, 3344 const APInt &DemandedElts, 3345 const SelectionDAG &DAG, 3346 unsigned Depth) const { 3347 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3348 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3349 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3350 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3351 "Should use MaskedValueIsZero if you don't know whether Op" 3352 " is a target node!"); 3353 Known.resetAll(); 3354 } 3355 3356 void TargetLowering::computeKnownBitsForTargetInstr( 3357 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3358 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3359 unsigned Depth) const { 3360 Known.resetAll(); 3361 } 3362 3363 void TargetLowering::computeKnownBitsForFrameIndex( 3364 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3365 // The low bits are known zero if the pointer is aligned. 3366 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3367 } 3368 3369 Align TargetLowering::computeKnownAlignForTargetInstr( 3370 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3371 unsigned Depth) const { 3372 return Align(1); 3373 } 3374 3375 /// This method can be implemented by targets that want to expose additional 3376 /// information about sign bits to the DAG Combiner. 3377 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3378 const APInt &, 3379 const SelectionDAG &, 3380 unsigned Depth) const { 3381 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3382 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3383 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3384 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3385 "Should use ComputeNumSignBits if you don't know whether Op" 3386 " is a target node!"); 3387 return 1; 3388 } 3389 3390 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3391 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3392 const MachineRegisterInfo &MRI, unsigned Depth) const { 3393 return 1; 3394 } 3395 3396 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3397 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3398 TargetLoweringOpt &TLO, unsigned Depth) const { 3399 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3400 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3401 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3402 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3403 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3404 " is a target node!"); 3405 return false; 3406 } 3407 3408 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3409 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3410 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3411 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3412 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3413 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3414 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3415 "Should use SimplifyDemandedBits if you don't know whether Op" 3416 " is a target node!"); 3417 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3418 return false; 3419 } 3420 3421 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3422 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3423 SelectionDAG &DAG, unsigned Depth) const { 3424 assert( 3425 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3426 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3427 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3428 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3429 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3430 " is a target node!"); 3431 return SDValue(); 3432 } 3433 3434 SDValue 3435 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3436 SDValue N1, MutableArrayRef<int> Mask, 3437 SelectionDAG &DAG) const { 3438 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3439 if (!LegalMask) { 3440 std::swap(N0, N1); 3441 ShuffleVectorSDNode::commuteMask(Mask); 3442 LegalMask = isShuffleMaskLegal(Mask, VT); 3443 } 3444 3445 if (!LegalMask) 3446 return SDValue(); 3447 3448 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3449 } 3450 3451 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3452 return nullptr; 3453 } 3454 3455 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3456 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3457 bool PoisonOnly, unsigned Depth) const { 3458 assert( 3459 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3460 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3461 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3462 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3463 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3464 " is a target node!"); 3465 return false; 3466 } 3467 3468 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3469 const SelectionDAG &DAG, 3470 bool SNaN, 3471 unsigned Depth) const { 3472 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3473 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3474 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3475 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3476 "Should use isKnownNeverNaN if you don't know whether Op" 3477 " is a target node!"); 3478 return false; 3479 } 3480 3481 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3482 const APInt &DemandedElts, 3483 APInt &UndefElts, 3484 unsigned Depth) const { 3485 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3486 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3487 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3488 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3489 "Should use isSplatValue if you don't know whether Op" 3490 " is a target node!"); 3491 return false; 3492 } 3493 3494 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3495 // work with truncating build vectors and vectors with elements of less than 3496 // 8 bits. 3497 bool TargetLowering::isConstTrueVal(SDValue N) const { 3498 if (!N) 3499 return false; 3500 3501 unsigned EltWidth; 3502 APInt CVal; 3503 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3504 /*AllowTruncation=*/true)) { 3505 CVal = CN->getAPIntValue(); 3506 EltWidth = N.getValueType().getScalarSizeInBits(); 3507 } else 3508 return false; 3509 3510 // If this is a truncating splat, truncate the splat value. 3511 // Otherwise, we may fail to match the expected values below. 3512 if (EltWidth < CVal.getBitWidth()) 3513 CVal = CVal.trunc(EltWidth); 3514 3515 switch (getBooleanContents(N.getValueType())) { 3516 case UndefinedBooleanContent: 3517 return CVal[0]; 3518 case ZeroOrOneBooleanContent: 3519 return CVal.isOne(); 3520 case ZeroOrNegativeOneBooleanContent: 3521 return CVal.isAllOnes(); 3522 } 3523 3524 llvm_unreachable("Invalid boolean contents"); 3525 } 3526 3527 bool TargetLowering::isConstFalseVal(SDValue N) const { 3528 if (!N) 3529 return false; 3530 3531 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3532 if (!CN) { 3533 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3534 if (!BV) 3535 return false; 3536 3537 // Only interested in constant splats, we don't care about undef 3538 // elements in identifying boolean constants and getConstantSplatNode 3539 // returns NULL if all ops are undef; 3540 CN = BV->getConstantSplatNode(); 3541 if (!CN) 3542 return false; 3543 } 3544 3545 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3546 return !CN->getAPIntValue()[0]; 3547 3548 return CN->isZero(); 3549 } 3550 3551 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3552 bool SExt) const { 3553 if (VT == MVT::i1) 3554 return N->isOne(); 3555 3556 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3557 switch (Cnt) { 3558 case TargetLowering::ZeroOrOneBooleanContent: 3559 // An extended value of 1 is always true, unless its original type is i1, 3560 // in which case it will be sign extended to -1. 3561 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3562 case TargetLowering::UndefinedBooleanContent: 3563 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3564 return N->isAllOnes() && SExt; 3565 } 3566 llvm_unreachable("Unexpected enumeration."); 3567 } 3568 3569 /// This helper function of SimplifySetCC tries to optimize the comparison when 3570 /// either operand of the SetCC node is a bitwise-and instruction. 3571 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3572 ISD::CondCode Cond, const SDLoc &DL, 3573 DAGCombinerInfo &DCI) const { 3574 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3575 std::swap(N0, N1); 3576 3577 SelectionDAG &DAG = DCI.DAG; 3578 EVT OpVT = N0.getValueType(); 3579 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3580 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3581 return SDValue(); 3582 3583 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3584 // iff everything but LSB is known zero: 3585 if (Cond == ISD::SETNE && isNullConstant(N1) && 3586 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3587 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3588 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3589 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3590 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3591 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3592 } 3593 3594 // Match these patterns in any of their permutations: 3595 // (X & Y) == Y 3596 // (X & Y) != Y 3597 SDValue X, Y; 3598 if (N0.getOperand(0) == N1) { 3599 X = N0.getOperand(1); 3600 Y = N0.getOperand(0); 3601 } else if (N0.getOperand(1) == N1) { 3602 X = N0.getOperand(0); 3603 Y = N0.getOperand(1); 3604 } else { 3605 return SDValue(); 3606 } 3607 3608 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3609 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3610 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3611 // Note that where Y is variable and is known to have at most one bit set 3612 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3613 // equivalent when Y == 0. 3614 assert(OpVT.isInteger()); 3615 Cond = ISD::getSetCCInverse(Cond, OpVT); 3616 if (DCI.isBeforeLegalizeOps() || 3617 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3618 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3619 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3620 // If the target supports an 'and-not' or 'and-complement' logic operation, 3621 // try to use that to make a comparison operation more efficient. 3622 // But don't do this transform if the mask is a single bit because there are 3623 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3624 // 'rlwinm' on PPC). 3625 3626 // Bail out if the compare operand that we want to turn into a zero is 3627 // already a zero (otherwise, infinite loop). 3628 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3629 if (YConst && YConst->isZero()) 3630 return SDValue(); 3631 3632 // Transform this into: ~X & Y == 0. 3633 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3634 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3635 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3636 } 3637 3638 return SDValue(); 3639 } 3640 3641 /// There are multiple IR patterns that could be checking whether certain 3642 /// truncation of a signed number would be lossy or not. The pattern which is 3643 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3644 /// We are looking for the following pattern: (KeptBits is a constant) 3645 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3646 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3647 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3648 /// We will unfold it into the natural trunc+sext pattern: 3649 /// ((%x << C) a>> C) dstcond %x 3650 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3651 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3652 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3653 const SDLoc &DL) const { 3654 // We must be comparing with a constant. 3655 ConstantSDNode *C1; 3656 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3657 return SDValue(); 3658 3659 // N0 should be: add %x, (1 << (KeptBits-1)) 3660 if (N0->getOpcode() != ISD::ADD) 3661 return SDValue(); 3662 3663 // And we must be 'add'ing a constant. 3664 ConstantSDNode *C01; 3665 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3666 return SDValue(); 3667 3668 SDValue X = N0->getOperand(0); 3669 EVT XVT = X.getValueType(); 3670 3671 // Validate constants ... 3672 3673 APInt I1 = C1->getAPIntValue(); 3674 3675 ISD::CondCode NewCond; 3676 if (Cond == ISD::CondCode::SETULT) { 3677 NewCond = ISD::CondCode::SETEQ; 3678 } else if (Cond == ISD::CondCode::SETULE) { 3679 NewCond = ISD::CondCode::SETEQ; 3680 // But need to 'canonicalize' the constant. 3681 I1 += 1; 3682 } else if (Cond == ISD::CondCode::SETUGT) { 3683 NewCond = ISD::CondCode::SETNE; 3684 // But need to 'canonicalize' the constant. 3685 I1 += 1; 3686 } else if (Cond == ISD::CondCode::SETUGE) { 3687 NewCond = ISD::CondCode::SETNE; 3688 } else 3689 return SDValue(); 3690 3691 APInt I01 = C01->getAPIntValue(); 3692 3693 auto checkConstants = [&I1, &I01]() -> bool { 3694 // Both of them must be power-of-two, and the constant from setcc is bigger. 3695 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3696 }; 3697 3698 if (checkConstants()) { 3699 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3700 } else { 3701 // What if we invert constants? (and the target predicate) 3702 I1.negate(); 3703 I01.negate(); 3704 assert(XVT.isInteger()); 3705 NewCond = getSetCCInverse(NewCond, XVT); 3706 if (!checkConstants()) 3707 return SDValue(); 3708 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3709 } 3710 3711 // They are power-of-two, so which bit is set? 3712 const unsigned KeptBits = I1.logBase2(); 3713 const unsigned KeptBitsMinusOne = I01.logBase2(); 3714 3715 // Magic! 3716 if (KeptBits != (KeptBitsMinusOne + 1)) 3717 return SDValue(); 3718 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3719 3720 // We don't want to do this in every single case. 3721 SelectionDAG &DAG = DCI.DAG; 3722 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3723 XVT, KeptBits)) 3724 return SDValue(); 3725 3726 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3727 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3728 3729 // Unfold into: ((%x << C) a>> C) cond %x 3730 // Where 'cond' will be either 'eq' or 'ne'. 3731 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3732 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3733 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3734 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3735 3736 return T2; 3737 } 3738 3739 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3740 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3741 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3742 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3743 assert(isConstOrConstSplat(N1C) && 3744 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3745 "Should be a comparison with 0."); 3746 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3747 "Valid only for [in]equality comparisons."); 3748 3749 unsigned NewShiftOpcode; 3750 SDValue X, C, Y; 3751 3752 SelectionDAG &DAG = DCI.DAG; 3753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3754 3755 // Look for '(C l>>/<< Y)'. 3756 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3757 // The shift should be one-use. 3758 if (!V.hasOneUse()) 3759 return false; 3760 unsigned OldShiftOpcode = V.getOpcode(); 3761 switch (OldShiftOpcode) { 3762 case ISD::SHL: 3763 NewShiftOpcode = ISD::SRL; 3764 break; 3765 case ISD::SRL: 3766 NewShiftOpcode = ISD::SHL; 3767 break; 3768 default: 3769 return false; // must be a logical shift. 3770 } 3771 // We should be shifting a constant. 3772 // FIXME: best to use isConstantOrConstantVector(). 3773 C = V.getOperand(0); 3774 ConstantSDNode *CC = 3775 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3776 if (!CC) 3777 return false; 3778 Y = V.getOperand(1); 3779 3780 ConstantSDNode *XC = 3781 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3782 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3783 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3784 }; 3785 3786 // LHS of comparison should be an one-use 'and'. 3787 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3788 return SDValue(); 3789 3790 X = N0.getOperand(0); 3791 SDValue Mask = N0.getOperand(1); 3792 3793 // 'and' is commutative! 3794 if (!Match(Mask)) { 3795 std::swap(X, Mask); 3796 if (!Match(Mask)) 3797 return SDValue(); 3798 } 3799 3800 EVT VT = X.getValueType(); 3801 3802 // Produce: 3803 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3804 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3805 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3806 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3807 return T2; 3808 } 3809 3810 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3811 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3812 /// handle the commuted versions of these patterns. 3813 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3814 ISD::CondCode Cond, const SDLoc &DL, 3815 DAGCombinerInfo &DCI) const { 3816 unsigned BOpcode = N0.getOpcode(); 3817 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3818 "Unexpected binop"); 3819 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3820 3821 // (X + Y) == X --> Y == 0 3822 // (X - Y) == X --> Y == 0 3823 // (X ^ Y) == X --> Y == 0 3824 SelectionDAG &DAG = DCI.DAG; 3825 EVT OpVT = N0.getValueType(); 3826 SDValue X = N0.getOperand(0); 3827 SDValue Y = N0.getOperand(1); 3828 if (X == N1) 3829 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3830 3831 if (Y != N1) 3832 return SDValue(); 3833 3834 // (X + Y) == Y --> X == 0 3835 // (X ^ Y) == Y --> X == 0 3836 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3837 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3838 3839 // The shift would not be valid if the operands are boolean (i1). 3840 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3841 return SDValue(); 3842 3843 // (X - Y) == Y --> X == Y << 1 3844 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3845 !DCI.isBeforeLegalize()); 3846 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3847 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3848 if (!DCI.isCalledByLegalizer()) 3849 DCI.AddToWorklist(YShl1.getNode()); 3850 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3851 } 3852 3853 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3854 SDValue N0, const APInt &C1, 3855 ISD::CondCode Cond, const SDLoc &dl, 3856 SelectionDAG &DAG) { 3857 // Look through truncs that don't change the value of a ctpop. 3858 // FIXME: Add vector support? Need to be careful with setcc result type below. 3859 SDValue CTPOP = N0; 3860 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3861 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3862 CTPOP = N0.getOperand(0); 3863 3864 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3865 return SDValue(); 3866 3867 EVT CTVT = CTPOP.getValueType(); 3868 SDValue CTOp = CTPOP.getOperand(0); 3869 3870 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3871 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3872 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3873 return SDValue(); 3874 3875 // (ctpop x) u< 2 -> (x & x-1) == 0 3876 // (ctpop x) u> 1 -> (x & x-1) != 0 3877 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3878 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3879 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3880 return SDValue(); 3881 if (C1 == 0 && (Cond == ISD::SETULT)) 3882 return SDValue(); // This is handled elsewhere. 3883 3884 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3885 3886 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3887 SDValue Result = CTOp; 3888 for (unsigned i = 0; i < Passes; i++) { 3889 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3890 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3891 } 3892 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3893 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3894 } 3895 3896 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3897 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3898 // For scalars, keep CTPOP if it is legal or custom. 3899 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3900 return SDValue(); 3901 // This is based on X86's custom lowering for CTPOP which produces more 3902 // instructions than the expansion here. 3903 3904 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3905 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3906 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3907 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3908 assert(CTVT.isInteger()); 3909 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3910 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3911 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3912 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3913 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3914 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3915 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3916 } 3917 3918 return SDValue(); 3919 } 3920 3921 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3922 ISD::CondCode Cond, const SDLoc &dl, 3923 SelectionDAG &DAG) { 3924 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3925 return SDValue(); 3926 3927 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3928 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3929 return SDValue(); 3930 3931 auto getRotateSource = [](SDValue X) { 3932 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3933 return X.getOperand(0); 3934 return SDValue(); 3935 }; 3936 3937 // Peek through a rotated value compared against 0 or -1: 3938 // (rot X, Y) == 0/-1 --> X == 0/-1 3939 // (rot X, Y) != 0/-1 --> X != 0/-1 3940 if (SDValue R = getRotateSource(N0)) 3941 return DAG.getSetCC(dl, VT, R, N1, Cond); 3942 3943 // Peek through an 'or' of a rotated value compared against 0: 3944 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 3945 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 3946 // 3947 // TODO: Add the 'and' with -1 sibling. 3948 // TODO: Recurse through a series of 'or' ops to find the rotate. 3949 EVT OpVT = N0.getValueType(); 3950 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 3951 if (SDValue R = getRotateSource(N0.getOperand(0))) { 3952 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 3953 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3954 } 3955 if (SDValue R = getRotateSource(N0.getOperand(1))) { 3956 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 3957 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3958 } 3959 } 3960 3961 return SDValue(); 3962 } 3963 3964 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 3965 ISD::CondCode Cond, const SDLoc &dl, 3966 SelectionDAG &DAG) { 3967 // If we are testing for all-bits-clear, we might be able to do that with 3968 // less shifting since bit-order does not matter. 3969 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3970 return SDValue(); 3971 3972 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3973 if (!C1 || !C1->isZero()) 3974 return SDValue(); 3975 3976 if (!N0.hasOneUse() || 3977 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 3978 return SDValue(); 3979 3980 unsigned BitWidth = N0.getScalarValueSizeInBits(); 3981 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 3982 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 3983 return SDValue(); 3984 3985 // Canonicalize fshr as fshl to reduce pattern-matching. 3986 unsigned ShAmt = ShAmtC->getZExtValue(); 3987 if (N0.getOpcode() == ISD::FSHR) 3988 ShAmt = BitWidth - ShAmt; 3989 3990 // Match an 'or' with a specific operand 'Other' in either commuted variant. 3991 SDValue X, Y; 3992 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 3993 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 3994 return false; 3995 if (Or.getOperand(0) == Other) { 3996 X = Or.getOperand(0); 3997 Y = Or.getOperand(1); 3998 return true; 3999 } 4000 if (Or.getOperand(1) == Other) { 4001 X = Or.getOperand(1); 4002 Y = Or.getOperand(0); 4003 return true; 4004 } 4005 return false; 4006 }; 4007 4008 EVT OpVT = N0.getValueType(); 4009 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4010 SDValue F0 = N0.getOperand(0); 4011 SDValue F1 = N0.getOperand(1); 4012 if (matchOr(F0, F1)) { 4013 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4014 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4015 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4016 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4017 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4018 } 4019 if (matchOr(F1, F0)) { 4020 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4021 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4022 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4023 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4024 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4025 } 4026 4027 return SDValue(); 4028 } 4029 4030 /// Try to simplify a setcc built with the specified operands and cc. If it is 4031 /// unable to simplify it, return a null SDValue. 4032 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4033 ISD::CondCode Cond, bool foldBooleans, 4034 DAGCombinerInfo &DCI, 4035 const SDLoc &dl) const { 4036 SelectionDAG &DAG = DCI.DAG; 4037 const DataLayout &Layout = DAG.getDataLayout(); 4038 EVT OpVT = N0.getValueType(); 4039 4040 // Constant fold or commute setcc. 4041 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4042 return Fold; 4043 4044 bool N0ConstOrSplat = 4045 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4046 bool N1ConstOrSplat = 4047 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4048 4049 // Ensure that the constant occurs on the RHS and fold constant comparisons. 4050 // TODO: Handle non-splat vector constants. All undef causes trouble. 4051 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4052 // infinite loop here when we encounter one. 4053 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4054 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4055 (DCI.isBeforeLegalizeOps() || 4056 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4057 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4058 4059 // If we have a subtract with the same 2 non-constant operands as this setcc 4060 // -- but in reverse order -- then try to commute the operands of this setcc 4061 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4062 // instruction on some targets. 4063 if (!N0ConstOrSplat && !N1ConstOrSplat && 4064 (DCI.isBeforeLegalizeOps() || 4065 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4066 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4067 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4068 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4069 4070 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4071 return V; 4072 4073 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4074 return V; 4075 4076 if (auto *N1C = isConstOrConstSplat(N1)) { 4077 const APInt &C1 = N1C->getAPIntValue(); 4078 4079 // Optimize some CTPOP cases. 4080 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4081 return V; 4082 4083 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4084 // equality comparison, then we're just comparing whether X itself is 4085 // zero. 4086 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4087 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4088 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4089 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4090 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4091 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4092 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4093 // (srl (ctlz x), 5) == 0 -> X != 0 4094 // (srl (ctlz x), 5) != 1 -> X != 0 4095 Cond = ISD::SETNE; 4096 } else { 4097 // (srl (ctlz x), 5) != 0 -> X == 0 4098 // (srl (ctlz x), 5) == 1 -> X == 0 4099 Cond = ISD::SETEQ; 4100 } 4101 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4102 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4103 Cond); 4104 } 4105 } 4106 } 4107 } 4108 4109 // FIXME: Support vectors. 4110 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4111 const APInt &C1 = N1C->getAPIntValue(); 4112 4113 // (zext x) == C --> x == (trunc C) 4114 // (sext x) == C --> x == (trunc C) 4115 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4116 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4117 unsigned MinBits = N0.getValueSizeInBits(); 4118 SDValue PreExt; 4119 bool Signed = false; 4120 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4121 // ZExt 4122 MinBits = N0->getOperand(0).getValueSizeInBits(); 4123 PreExt = N0->getOperand(0); 4124 } else if (N0->getOpcode() == ISD::AND) { 4125 // DAGCombine turns costly ZExts into ANDs 4126 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4127 if ((C->getAPIntValue()+1).isPowerOf2()) { 4128 MinBits = C->getAPIntValue().countTrailingOnes(); 4129 PreExt = N0->getOperand(0); 4130 } 4131 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4132 // SExt 4133 MinBits = N0->getOperand(0).getValueSizeInBits(); 4134 PreExt = N0->getOperand(0); 4135 Signed = true; 4136 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4137 // ZEXTLOAD / SEXTLOAD 4138 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4139 MinBits = LN0->getMemoryVT().getSizeInBits(); 4140 PreExt = N0; 4141 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4142 Signed = true; 4143 MinBits = LN0->getMemoryVT().getSizeInBits(); 4144 PreExt = N0; 4145 } 4146 } 4147 4148 // Figure out how many bits we need to preserve this constant. 4149 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4150 4151 // Make sure we're not losing bits from the constant. 4152 if (MinBits > 0 && 4153 MinBits < C1.getBitWidth() && 4154 MinBits >= ReqdBits) { 4155 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4156 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4157 // Will get folded away. 4158 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4159 if (MinBits == 1 && C1 == 1) 4160 // Invert the condition. 4161 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4162 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4163 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4164 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4165 } 4166 4167 // If truncating the setcc operands is not desirable, we can still 4168 // simplify the expression in some cases: 4169 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4170 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4171 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4172 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4173 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4174 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4175 SDValue TopSetCC = N0->getOperand(0); 4176 unsigned N0Opc = N0->getOpcode(); 4177 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4178 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4179 TopSetCC.getOpcode() == ISD::SETCC && 4180 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4181 (isConstFalseVal(N1) || 4182 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4183 4184 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4185 (!N1C->isZero() && Cond == ISD::SETNE); 4186 4187 if (!Inverse) 4188 return TopSetCC; 4189 4190 ISD::CondCode InvCond = ISD::getSetCCInverse( 4191 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4192 TopSetCC.getOperand(0).getValueType()); 4193 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4194 TopSetCC.getOperand(1), 4195 InvCond); 4196 } 4197 } 4198 } 4199 4200 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4201 // equality or unsigned, and all 1 bits of the const are in the same 4202 // partial word, see if we can shorten the load. 4203 if (DCI.isBeforeLegalize() && 4204 !ISD::isSignedIntSetCC(Cond) && 4205 N0.getOpcode() == ISD::AND && C1 == 0 && 4206 N0.getNode()->hasOneUse() && 4207 isa<LoadSDNode>(N0.getOperand(0)) && 4208 N0.getOperand(0).getNode()->hasOneUse() && 4209 isa<ConstantSDNode>(N0.getOperand(1))) { 4210 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4211 APInt bestMask; 4212 unsigned bestWidth = 0, bestOffset = 0; 4213 if (Lod->isSimple() && Lod->isUnindexed()) { 4214 unsigned origWidth = N0.getValueSizeInBits(); 4215 unsigned maskWidth = origWidth; 4216 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4217 // 8 bits, but have to be careful... 4218 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4219 origWidth = Lod->getMemoryVT().getSizeInBits(); 4220 const APInt &Mask = N0.getConstantOperandAPInt(1); 4221 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4222 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4223 for (unsigned offset=0; offset<origWidth/width; offset++) { 4224 if (Mask.isSubsetOf(newMask)) { 4225 if (Layout.isLittleEndian()) 4226 bestOffset = (uint64_t)offset * (width/8); 4227 else 4228 bestOffset = (origWidth/width - offset - 1) * (width/8); 4229 bestMask = Mask.lshr(offset * (width/8) * 8); 4230 bestWidth = width; 4231 break; 4232 } 4233 newMask <<= width; 4234 } 4235 } 4236 } 4237 if (bestWidth) { 4238 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4239 if (newVT.isRound() && 4240 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4241 SDValue Ptr = Lod->getBasePtr(); 4242 if (bestOffset != 0) 4243 Ptr = 4244 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4245 SDValue NewLoad = 4246 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4247 Lod->getPointerInfo().getWithOffset(bestOffset), 4248 Lod->getOriginalAlign()); 4249 return DAG.getSetCC(dl, VT, 4250 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4251 DAG.getConstant(bestMask.trunc(bestWidth), 4252 dl, newVT)), 4253 DAG.getConstant(0LL, dl, newVT), Cond); 4254 } 4255 } 4256 } 4257 4258 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4259 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4260 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4261 4262 // If the comparison constant has bits in the upper part, the 4263 // zero-extended value could never match. 4264 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4265 C1.getBitWidth() - InSize))) { 4266 switch (Cond) { 4267 case ISD::SETUGT: 4268 case ISD::SETUGE: 4269 case ISD::SETEQ: 4270 return DAG.getConstant(0, dl, VT); 4271 case ISD::SETULT: 4272 case ISD::SETULE: 4273 case ISD::SETNE: 4274 return DAG.getConstant(1, dl, VT); 4275 case ISD::SETGT: 4276 case ISD::SETGE: 4277 // True if the sign bit of C1 is set. 4278 return DAG.getConstant(C1.isNegative(), dl, VT); 4279 case ISD::SETLT: 4280 case ISD::SETLE: 4281 // True if the sign bit of C1 isn't set. 4282 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4283 default: 4284 break; 4285 } 4286 } 4287 4288 // Otherwise, we can perform the comparison with the low bits. 4289 switch (Cond) { 4290 case ISD::SETEQ: 4291 case ISD::SETNE: 4292 case ISD::SETUGT: 4293 case ISD::SETUGE: 4294 case ISD::SETULT: 4295 case ISD::SETULE: { 4296 EVT newVT = N0.getOperand(0).getValueType(); 4297 if (DCI.isBeforeLegalizeOps() || 4298 (isOperationLegal(ISD::SETCC, newVT) && 4299 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4300 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4301 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4302 4303 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4304 NewConst, Cond); 4305 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4306 } 4307 break; 4308 } 4309 default: 4310 break; // todo, be more careful with signed comparisons 4311 } 4312 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4313 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4314 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4315 OpVT)) { 4316 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4317 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4318 EVT ExtDstTy = N0.getValueType(); 4319 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4320 4321 // If the constant doesn't fit into the number of bits for the source of 4322 // the sign extension, it is impossible for both sides to be equal. 4323 if (C1.getMinSignedBits() > ExtSrcTyBits) 4324 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4325 4326 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4327 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4328 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4329 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4330 DAG.getConstant(Imm, dl, ExtDstTy)); 4331 if (!DCI.isCalledByLegalizer()) 4332 DCI.AddToWorklist(ZextOp.getNode()); 4333 // Otherwise, make this a use of a zext. 4334 return DAG.getSetCC(dl, VT, ZextOp, 4335 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4336 } else if ((N1C->isZero() || N1C->isOne()) && 4337 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4338 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4339 if (N0.getOpcode() == ISD::SETCC && 4340 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4341 (N0.getValueType() == MVT::i1 || 4342 getBooleanContents(N0.getOperand(0).getValueType()) == 4343 ZeroOrOneBooleanContent)) { 4344 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4345 if (TrueWhenTrue) 4346 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4347 // Invert the condition. 4348 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4349 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4350 if (DCI.isBeforeLegalizeOps() || 4351 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4352 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4353 } 4354 4355 if ((N0.getOpcode() == ISD::XOR || 4356 (N0.getOpcode() == ISD::AND && 4357 N0.getOperand(0).getOpcode() == ISD::XOR && 4358 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4359 isOneConstant(N0.getOperand(1))) { 4360 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4361 // can only do this if the top bits are known zero. 4362 unsigned BitWidth = N0.getValueSizeInBits(); 4363 if (DAG.MaskedValueIsZero(N0, 4364 APInt::getHighBitsSet(BitWidth, 4365 BitWidth-1))) { 4366 // Okay, get the un-inverted input value. 4367 SDValue Val; 4368 if (N0.getOpcode() == ISD::XOR) { 4369 Val = N0.getOperand(0); 4370 } else { 4371 assert(N0.getOpcode() == ISD::AND && 4372 N0.getOperand(0).getOpcode() == ISD::XOR); 4373 // ((X^1)&1)^1 -> X & 1 4374 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4375 N0.getOperand(0).getOperand(0), 4376 N0.getOperand(1)); 4377 } 4378 4379 return DAG.getSetCC(dl, VT, Val, N1, 4380 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4381 } 4382 } else if (N1C->isOne()) { 4383 SDValue Op0 = N0; 4384 if (Op0.getOpcode() == ISD::TRUNCATE) 4385 Op0 = Op0.getOperand(0); 4386 4387 if ((Op0.getOpcode() == ISD::XOR) && 4388 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4389 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4390 SDValue XorLHS = Op0.getOperand(0); 4391 SDValue XorRHS = Op0.getOperand(1); 4392 // Ensure that the input setccs return an i1 type or 0/1 value. 4393 if (Op0.getValueType() == MVT::i1 || 4394 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4395 ZeroOrOneBooleanContent && 4396 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4397 ZeroOrOneBooleanContent)) { 4398 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4399 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4400 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4401 } 4402 } 4403 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4404 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4405 if (Op0.getValueType().bitsGT(VT)) 4406 Op0 = DAG.getNode(ISD::AND, dl, VT, 4407 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4408 DAG.getConstant(1, dl, VT)); 4409 else if (Op0.getValueType().bitsLT(VT)) 4410 Op0 = DAG.getNode(ISD::AND, dl, VT, 4411 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4412 DAG.getConstant(1, dl, VT)); 4413 4414 return DAG.getSetCC(dl, VT, Op0, 4415 DAG.getConstant(0, dl, Op0.getValueType()), 4416 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4417 } 4418 if (Op0.getOpcode() == ISD::AssertZext && 4419 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4420 return DAG.getSetCC(dl, VT, Op0, 4421 DAG.getConstant(0, dl, Op0.getValueType()), 4422 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4423 } 4424 } 4425 4426 // Given: 4427 // icmp eq/ne (urem %x, %y), 0 4428 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4429 // icmp eq/ne %x, 0 4430 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4431 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4432 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4433 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4434 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4435 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4436 } 4437 4438 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4439 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4440 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4441 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4442 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4443 N1C && N1C->isAllOnes()) { 4444 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4445 DAG.getConstant(0, dl, OpVT), 4446 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4447 } 4448 4449 if (SDValue V = 4450 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4451 return V; 4452 } 4453 4454 // These simplifications apply to splat vectors as well. 4455 // TODO: Handle more splat vector cases. 4456 if (auto *N1C = isConstOrConstSplat(N1)) { 4457 const APInt &C1 = N1C->getAPIntValue(); 4458 4459 APInt MinVal, MaxVal; 4460 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4461 if (ISD::isSignedIntSetCC(Cond)) { 4462 MinVal = APInt::getSignedMinValue(OperandBitSize); 4463 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4464 } else { 4465 MinVal = APInt::getMinValue(OperandBitSize); 4466 MaxVal = APInt::getMaxValue(OperandBitSize); 4467 } 4468 4469 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4470 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4471 // X >= MIN --> true 4472 if (C1 == MinVal) 4473 return DAG.getBoolConstant(true, dl, VT, OpVT); 4474 4475 if (!VT.isVector()) { // TODO: Support this for vectors. 4476 // X >= C0 --> X > (C0 - 1) 4477 APInt C = C1 - 1; 4478 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4479 if ((DCI.isBeforeLegalizeOps() || 4480 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4481 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4482 isLegalICmpImmediate(C.getSExtValue())))) { 4483 return DAG.getSetCC(dl, VT, N0, 4484 DAG.getConstant(C, dl, N1.getValueType()), 4485 NewCC); 4486 } 4487 } 4488 } 4489 4490 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4491 // X <= MAX --> true 4492 if (C1 == MaxVal) 4493 return DAG.getBoolConstant(true, dl, VT, OpVT); 4494 4495 // X <= C0 --> X < (C0 + 1) 4496 if (!VT.isVector()) { // TODO: Support this for vectors. 4497 APInt C = C1 + 1; 4498 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4499 if ((DCI.isBeforeLegalizeOps() || 4500 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4501 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4502 isLegalICmpImmediate(C.getSExtValue())))) { 4503 return DAG.getSetCC(dl, VT, N0, 4504 DAG.getConstant(C, dl, N1.getValueType()), 4505 NewCC); 4506 } 4507 } 4508 } 4509 4510 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4511 if (C1 == MinVal) 4512 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4513 4514 // TODO: Support this for vectors after legalize ops. 4515 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4516 // Canonicalize setlt X, Max --> setne X, Max 4517 if (C1 == MaxVal) 4518 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4519 4520 // If we have setult X, 1, turn it into seteq X, 0 4521 if (C1 == MinVal+1) 4522 return DAG.getSetCC(dl, VT, N0, 4523 DAG.getConstant(MinVal, dl, N0.getValueType()), 4524 ISD::SETEQ); 4525 } 4526 } 4527 4528 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4529 if (C1 == MaxVal) 4530 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4531 4532 // TODO: Support this for vectors after legalize ops. 4533 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4534 // Canonicalize setgt X, Min --> setne X, Min 4535 if (C1 == MinVal) 4536 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4537 4538 // If we have setugt X, Max-1, turn it into seteq X, Max 4539 if (C1 == MaxVal-1) 4540 return DAG.getSetCC(dl, VT, N0, 4541 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4542 ISD::SETEQ); 4543 } 4544 } 4545 4546 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4547 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4548 if (C1.isZero()) 4549 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4550 VT, N0, N1, Cond, DCI, dl)) 4551 return CC; 4552 4553 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4554 // For example, when high 32-bits of i64 X are known clear: 4555 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4556 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4557 bool CmpZero = N1C->getAPIntValue().isZero(); 4558 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4559 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4560 // Match or(lo,shl(hi,bw/2)) pattern. 4561 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4562 unsigned EltBits = V.getScalarValueSizeInBits(); 4563 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4564 return false; 4565 SDValue LHS = V.getOperand(0); 4566 SDValue RHS = V.getOperand(1); 4567 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4568 // Unshifted element must have zero upperbits. 4569 if (RHS.getOpcode() == ISD::SHL && 4570 isa<ConstantSDNode>(RHS.getOperand(1)) && 4571 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4572 DAG.MaskedValueIsZero(LHS, HiBits)) { 4573 Lo = LHS; 4574 Hi = RHS.getOperand(0); 4575 return true; 4576 } 4577 if (LHS.getOpcode() == ISD::SHL && 4578 isa<ConstantSDNode>(LHS.getOperand(1)) && 4579 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4580 DAG.MaskedValueIsZero(RHS, HiBits)) { 4581 Lo = RHS; 4582 Hi = LHS.getOperand(0); 4583 return true; 4584 } 4585 return false; 4586 }; 4587 4588 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4589 unsigned EltBits = N0.getScalarValueSizeInBits(); 4590 unsigned HalfBits = EltBits / 2; 4591 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4592 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4593 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4594 SDValue NewN0 = 4595 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4596 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4597 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4598 }; 4599 4600 SDValue Lo, Hi; 4601 if (IsConcat(N0, Lo, Hi)) 4602 return MergeConcat(Lo, Hi); 4603 4604 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4605 SDValue Lo0, Lo1, Hi0, Hi1; 4606 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4607 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4608 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4609 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4610 } 4611 } 4612 } 4613 } 4614 4615 // If we have "setcc X, C0", check to see if we can shrink the immediate 4616 // by changing cc. 4617 // TODO: Support this for vectors after legalize ops. 4618 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4619 // SETUGT X, SINTMAX -> SETLT X, 0 4620 // SETUGE X, SINTMIN -> SETLT X, 0 4621 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4622 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4623 return DAG.getSetCC(dl, VT, N0, 4624 DAG.getConstant(0, dl, N1.getValueType()), 4625 ISD::SETLT); 4626 4627 // SETULT X, SINTMIN -> SETGT X, -1 4628 // SETULE X, SINTMAX -> SETGT X, -1 4629 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4630 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4631 return DAG.getSetCC(dl, VT, N0, 4632 DAG.getAllOnesConstant(dl, N1.getValueType()), 4633 ISD::SETGT); 4634 } 4635 } 4636 4637 // Back to non-vector simplifications. 4638 // TODO: Can we do these for vector splats? 4639 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4641 const APInt &C1 = N1C->getAPIntValue(); 4642 EVT ShValTy = N0.getValueType(); 4643 4644 // Fold bit comparisons when we can. This will result in an 4645 // incorrect value when boolean false is negative one, unless 4646 // the bitsize is 1 in which case the false value is the same 4647 // in practice regardless of the representation. 4648 if ((VT.getSizeInBits() == 1 || 4649 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4650 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4651 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4652 N0.getOpcode() == ISD::AND) { 4653 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4654 EVT ShiftTy = 4655 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4656 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4657 // Perform the xform if the AND RHS is a single bit. 4658 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4659 if (AndRHS->getAPIntValue().isPowerOf2() && 4660 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4661 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4662 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4663 DAG.getConstant(ShCt, dl, ShiftTy))); 4664 } 4665 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4666 // (X & 8) == 8 --> (X & 8) >> 3 4667 // Perform the xform if C1 is a single bit. 4668 unsigned ShCt = C1.logBase2(); 4669 if (C1.isPowerOf2() && 4670 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4671 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4672 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4673 DAG.getConstant(ShCt, dl, ShiftTy))); 4674 } 4675 } 4676 } 4677 } 4678 4679 if (C1.getMinSignedBits() <= 64 && 4680 !isLegalICmpImmediate(C1.getSExtValue())) { 4681 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4682 // (X & -256) == 256 -> (X >> 8) == 1 4683 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4684 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4685 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4686 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4687 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4688 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4689 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4690 SDValue Shift = 4691 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4692 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4693 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4694 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4695 } 4696 } 4697 } 4698 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4699 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4700 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4701 // X < 0x100000000 -> (X >> 32) < 1 4702 // X >= 0x100000000 -> (X >> 32) >= 1 4703 // X <= 0x0ffffffff -> (X >> 32) < 1 4704 // X > 0x0ffffffff -> (X >> 32) >= 1 4705 unsigned ShiftBits; 4706 APInt NewC = C1; 4707 ISD::CondCode NewCond = Cond; 4708 if (AdjOne) { 4709 ShiftBits = C1.countTrailingOnes(); 4710 NewC = NewC + 1; 4711 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4712 } else { 4713 ShiftBits = C1.countTrailingZeros(); 4714 } 4715 NewC.lshrInPlace(ShiftBits); 4716 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4717 isLegalICmpImmediate(NewC.getSExtValue()) && 4718 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4719 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4720 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4721 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4722 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4723 } 4724 } 4725 } 4726 } 4727 4728 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4729 auto *CFP = cast<ConstantFPSDNode>(N1); 4730 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4731 4732 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4733 // constant if knowing that the operand is non-nan is enough. We prefer to 4734 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4735 // materialize 0.0. 4736 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4737 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4738 4739 // setcc (fneg x), C -> setcc swap(pred) x, -C 4740 if (N0.getOpcode() == ISD::FNEG) { 4741 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4742 if (DCI.isBeforeLegalizeOps() || 4743 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4744 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4745 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4746 } 4747 } 4748 4749 // If the condition is not legal, see if we can find an equivalent one 4750 // which is legal. 4751 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4752 // If the comparison was an awkward floating-point == or != and one of 4753 // the comparison operands is infinity or negative infinity, convert the 4754 // condition to a less-awkward <= or >=. 4755 if (CFP->getValueAPF().isInfinity()) { 4756 bool IsNegInf = CFP->getValueAPF().isNegative(); 4757 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4758 switch (Cond) { 4759 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4760 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4761 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4762 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4763 default: break; 4764 } 4765 if (NewCond != ISD::SETCC_INVALID && 4766 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4767 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4768 } 4769 } 4770 } 4771 4772 if (N0 == N1) { 4773 // The sext(setcc()) => setcc() optimization relies on the appropriate 4774 // constant being emitted. 4775 assert(!N0.getValueType().isInteger() && 4776 "Integer types should be handled by FoldSetCC"); 4777 4778 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4779 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4780 if (UOF == 2) // FP operators that are undefined on NaNs. 4781 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4782 if (UOF == unsigned(EqTrue)) 4783 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4784 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4785 // if it is not already. 4786 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4787 if (NewCond != Cond && 4788 (DCI.isBeforeLegalizeOps() || 4789 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4790 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4791 } 4792 4793 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4794 N0.getValueType().isInteger()) { 4795 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4796 N0.getOpcode() == ISD::XOR) { 4797 // Simplify (X+Y) == (X+Z) --> Y == Z 4798 if (N0.getOpcode() == N1.getOpcode()) { 4799 if (N0.getOperand(0) == N1.getOperand(0)) 4800 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4801 if (N0.getOperand(1) == N1.getOperand(1)) 4802 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4803 if (isCommutativeBinOp(N0.getOpcode())) { 4804 // If X op Y == Y op X, try other combinations. 4805 if (N0.getOperand(0) == N1.getOperand(1)) 4806 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4807 Cond); 4808 if (N0.getOperand(1) == N1.getOperand(0)) 4809 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4810 Cond); 4811 } 4812 } 4813 4814 // If RHS is a legal immediate value for a compare instruction, we need 4815 // to be careful about increasing register pressure needlessly. 4816 bool LegalRHSImm = false; 4817 4818 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4819 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4820 // Turn (X+C1) == C2 --> X == C2-C1 4821 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4822 return DAG.getSetCC( 4823 dl, VT, N0.getOperand(0), 4824 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4825 dl, N0.getValueType()), 4826 Cond); 4827 4828 // Turn (X^C1) == C2 --> X == C1^C2 4829 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4830 return DAG.getSetCC( 4831 dl, VT, N0.getOperand(0), 4832 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4833 dl, N0.getValueType()), 4834 Cond); 4835 } 4836 4837 // Turn (C1-X) == C2 --> X == C1-C2 4838 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4839 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4840 return DAG.getSetCC( 4841 dl, VT, N0.getOperand(1), 4842 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4843 dl, N0.getValueType()), 4844 Cond); 4845 4846 // Could RHSC fold directly into a compare? 4847 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4848 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4849 } 4850 4851 // (X+Y) == X --> Y == 0 and similar folds. 4852 // Don't do this if X is an immediate that can fold into a cmp 4853 // instruction and X+Y has other uses. It could be an induction variable 4854 // chain, and the transform would increase register pressure. 4855 if (!LegalRHSImm || N0.hasOneUse()) 4856 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4857 return V; 4858 } 4859 4860 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4861 N1.getOpcode() == ISD::XOR) 4862 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4863 return V; 4864 4865 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4866 return V; 4867 } 4868 4869 // Fold remainder of division by a constant. 4870 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4871 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4872 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4873 4874 // When division is cheap or optimizing for minimum size, 4875 // fall through to DIVREM creation by skipping this fold. 4876 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4877 if (N0.getOpcode() == ISD::UREM) { 4878 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4879 return Folded; 4880 } else if (N0.getOpcode() == ISD::SREM) { 4881 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4882 return Folded; 4883 } 4884 } 4885 } 4886 4887 // Fold away ALL boolean setcc's. 4888 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4889 SDValue Temp; 4890 switch (Cond) { 4891 default: llvm_unreachable("Unknown integer setcc!"); 4892 case ISD::SETEQ: // X == Y -> ~(X^Y) 4893 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4894 N0 = DAG.getNOT(dl, Temp, OpVT); 4895 if (!DCI.isCalledByLegalizer()) 4896 DCI.AddToWorklist(Temp.getNode()); 4897 break; 4898 case ISD::SETNE: // X != Y --> (X^Y) 4899 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4900 break; 4901 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4902 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4903 Temp = DAG.getNOT(dl, N0, OpVT); 4904 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4905 if (!DCI.isCalledByLegalizer()) 4906 DCI.AddToWorklist(Temp.getNode()); 4907 break; 4908 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4909 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4910 Temp = DAG.getNOT(dl, N1, OpVT); 4911 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4912 if (!DCI.isCalledByLegalizer()) 4913 DCI.AddToWorklist(Temp.getNode()); 4914 break; 4915 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4916 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4917 Temp = DAG.getNOT(dl, N0, OpVT); 4918 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4919 if (!DCI.isCalledByLegalizer()) 4920 DCI.AddToWorklist(Temp.getNode()); 4921 break; 4922 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4923 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4924 Temp = DAG.getNOT(dl, N1, OpVT); 4925 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4926 break; 4927 } 4928 if (VT.getScalarType() != MVT::i1) { 4929 if (!DCI.isCalledByLegalizer()) 4930 DCI.AddToWorklist(N0.getNode()); 4931 // FIXME: If running after legalize, we probably can't do this. 4932 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4933 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4934 } 4935 return N0; 4936 } 4937 4938 // Could not fold it. 4939 return SDValue(); 4940 } 4941 4942 /// Returns true (and the GlobalValue and the offset) if the node is a 4943 /// GlobalAddress + offset. 4944 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4945 int64_t &Offset) const { 4946 4947 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4948 4949 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4950 GA = GASD->getGlobal(); 4951 Offset += GASD->getOffset(); 4952 return true; 4953 } 4954 4955 if (N->getOpcode() == ISD::ADD) { 4956 SDValue N1 = N->getOperand(0); 4957 SDValue N2 = N->getOperand(1); 4958 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4959 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4960 Offset += V->getSExtValue(); 4961 return true; 4962 } 4963 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4964 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4965 Offset += V->getSExtValue(); 4966 return true; 4967 } 4968 } 4969 } 4970 4971 return false; 4972 } 4973 4974 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4975 DAGCombinerInfo &DCI) const { 4976 // Default implementation: no optimization. 4977 return SDValue(); 4978 } 4979 4980 //===----------------------------------------------------------------------===// 4981 // Inline Assembler Implementation Methods 4982 //===----------------------------------------------------------------------===// 4983 4984 TargetLowering::ConstraintType 4985 TargetLowering::getConstraintType(StringRef Constraint) const { 4986 unsigned S = Constraint.size(); 4987 4988 if (S == 1) { 4989 switch (Constraint[0]) { 4990 default: break; 4991 case 'r': 4992 return C_RegisterClass; 4993 case 'm': // memory 4994 case 'o': // offsetable 4995 case 'V': // not offsetable 4996 return C_Memory; 4997 case 'p': // Address. 4998 return C_Address; 4999 case 'n': // Simple Integer 5000 case 'E': // Floating Point Constant 5001 case 'F': // Floating Point Constant 5002 return C_Immediate; 5003 case 'i': // Simple Integer or Relocatable Constant 5004 case 's': // Relocatable Constant 5005 case 'X': // Allow ANY value. 5006 case 'I': // Target registers. 5007 case 'J': 5008 case 'K': 5009 case 'L': 5010 case 'M': 5011 case 'N': 5012 case 'O': 5013 case 'P': 5014 case '<': 5015 case '>': 5016 return C_Other; 5017 } 5018 } 5019 5020 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5021 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5022 return C_Memory; 5023 return C_Register; 5024 } 5025 return C_Unknown; 5026 } 5027 5028 /// Try to replace an X constraint, which matches anything, with another that 5029 /// has more specific requirements based on the type of the corresponding 5030 /// operand. 5031 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5032 if (ConstraintVT.isInteger()) 5033 return "r"; 5034 if (ConstraintVT.isFloatingPoint()) 5035 return "f"; // works for many targets 5036 return nullptr; 5037 } 5038 5039 SDValue TargetLowering::LowerAsmOutputForConstraint( 5040 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 5041 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5042 return SDValue(); 5043 } 5044 5045 /// Lower the specified operand into the Ops vector. 5046 /// If it is invalid, don't add anything to Ops. 5047 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5048 std::string &Constraint, 5049 std::vector<SDValue> &Ops, 5050 SelectionDAG &DAG) const { 5051 5052 if (Constraint.length() > 1) return; 5053 5054 char ConstraintLetter = Constraint[0]; 5055 switch (ConstraintLetter) { 5056 default: break; 5057 case 'X': // Allows any operand 5058 case 'i': // Simple Integer or Relocatable Constant 5059 case 'n': // Simple Integer 5060 case 's': { // Relocatable Constant 5061 5062 ConstantSDNode *C; 5063 uint64_t Offset = 0; 5064 5065 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5066 // etc., since getelementpointer is variadic. We can't use 5067 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5068 // while in this case the GA may be furthest from the root node which is 5069 // likely an ISD::ADD. 5070 while (true) { 5071 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5072 // gcc prints these as sign extended. Sign extend value to 64 bits 5073 // now; without this it would get ZExt'd later in 5074 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5075 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5076 BooleanContent BCont = getBooleanContents(MVT::i64); 5077 ISD::NodeType ExtOpc = 5078 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5079 int64_t ExtVal = 5080 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5081 Ops.push_back( 5082 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5083 return; 5084 } 5085 if (ConstraintLetter != 'n') { 5086 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5087 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5088 GA->getValueType(0), 5089 Offset + GA->getOffset())); 5090 return; 5091 } 5092 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5093 Ops.push_back(DAG.getTargetBlockAddress( 5094 BA->getBlockAddress(), BA->getValueType(0), 5095 Offset + BA->getOffset(), BA->getTargetFlags())); 5096 return; 5097 } 5098 if (isa<BasicBlockSDNode>(Op)) { 5099 Ops.push_back(Op); 5100 return; 5101 } 5102 } 5103 const unsigned OpCode = Op.getOpcode(); 5104 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5105 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5106 Op = Op.getOperand(1); 5107 // Subtraction is not commutative. 5108 else if (OpCode == ISD::ADD && 5109 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5110 Op = Op.getOperand(0); 5111 else 5112 return; 5113 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5114 continue; 5115 } 5116 return; 5117 } 5118 break; 5119 } 5120 } 5121 } 5122 5123 std::pair<unsigned, const TargetRegisterClass *> 5124 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5125 StringRef Constraint, 5126 MVT VT) const { 5127 if (Constraint.empty() || Constraint[0] != '{') 5128 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5129 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5130 5131 // Remove the braces from around the name. 5132 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5133 5134 std::pair<unsigned, const TargetRegisterClass *> R = 5135 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5136 5137 // Figure out which register class contains this reg. 5138 for (const TargetRegisterClass *RC : RI->regclasses()) { 5139 // If none of the value types for this register class are valid, we 5140 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5141 if (!isLegalRC(*RI, *RC)) 5142 continue; 5143 5144 for (const MCPhysReg &PR : *RC) { 5145 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5146 std::pair<unsigned, const TargetRegisterClass *> S = 5147 std::make_pair(PR, RC); 5148 5149 // If this register class has the requested value type, return it, 5150 // otherwise keep searching and return the first class found 5151 // if no other is found which explicitly has the requested type. 5152 if (RI->isTypeLegalForClass(*RC, VT)) 5153 return S; 5154 if (!R.second) 5155 R = S; 5156 } 5157 } 5158 } 5159 5160 return R; 5161 } 5162 5163 //===----------------------------------------------------------------------===// 5164 // Constraint Selection. 5165 5166 /// Return true of this is an input operand that is a matching constraint like 5167 /// "4". 5168 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5169 assert(!ConstraintCode.empty() && "No known constraint!"); 5170 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5171 } 5172 5173 /// If this is an input matching constraint, this method returns the output 5174 /// operand it matches. 5175 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5176 assert(!ConstraintCode.empty() && "No known constraint!"); 5177 return atoi(ConstraintCode.c_str()); 5178 } 5179 5180 /// Split up the constraint string from the inline assembly value into the 5181 /// specific constraints and their prefixes, and also tie in the associated 5182 /// operand values. 5183 /// If this returns an empty vector, and if the constraint string itself 5184 /// isn't empty, there was an error parsing. 5185 TargetLowering::AsmOperandInfoVector 5186 TargetLowering::ParseConstraints(const DataLayout &DL, 5187 const TargetRegisterInfo *TRI, 5188 const CallBase &Call) const { 5189 /// Information about all of the constraints. 5190 AsmOperandInfoVector ConstraintOperands; 5191 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5192 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5193 5194 // Do a prepass over the constraints, canonicalizing them, and building up the 5195 // ConstraintOperands list. 5196 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5197 unsigned ResNo = 0; // ResNo - The result number of the next output. 5198 5199 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5200 ConstraintOperands.emplace_back(std::move(CI)); 5201 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5202 5203 // Update multiple alternative constraint count. 5204 if (OpInfo.multipleAlternatives.size() > maCount) 5205 maCount = OpInfo.multipleAlternatives.size(); 5206 5207 OpInfo.ConstraintVT = MVT::Other; 5208 5209 // Compute the value type for each operand. 5210 switch (OpInfo.Type) { 5211 case InlineAsm::isOutput: 5212 // Indirect outputs just consume an argument. 5213 if (OpInfo.isIndirect) { 5214 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5215 break; 5216 } 5217 5218 // The return value of the call is this value. As such, there is no 5219 // corresponding argument. 5220 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5221 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5222 OpInfo.ConstraintVT = 5223 getSimpleValueType(DL, STy->getElementType(ResNo)); 5224 } else { 5225 assert(ResNo == 0 && "Asm only has one result!"); 5226 OpInfo.ConstraintVT = 5227 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5228 } 5229 ++ResNo; 5230 break; 5231 case InlineAsm::isInput: 5232 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5233 break; 5234 case InlineAsm::isClobber: 5235 // Nothing to do. 5236 break; 5237 } 5238 5239 if (OpInfo.CallOperandVal) { 5240 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5241 if (OpInfo.isIndirect) { 5242 OpTy = Call.getParamElementType(ArgNo); 5243 assert(OpTy && "Indirect operand must have elementtype attribute"); 5244 } 5245 5246 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5247 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5248 if (STy->getNumElements() == 1) 5249 OpTy = STy->getElementType(0); 5250 5251 // If OpTy is not a single value, it may be a struct/union that we 5252 // can tile with integers. 5253 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5254 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5255 switch (BitSize) { 5256 default: break; 5257 case 1: 5258 case 8: 5259 case 16: 5260 case 32: 5261 case 64: 5262 case 128: 5263 OpInfo.ConstraintVT = 5264 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 5265 break; 5266 } 5267 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 5268 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 5269 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 5270 } else { 5271 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 5272 } 5273 5274 ArgNo++; 5275 } 5276 } 5277 5278 // If we have multiple alternative constraints, select the best alternative. 5279 if (!ConstraintOperands.empty()) { 5280 if (maCount) { 5281 unsigned bestMAIndex = 0; 5282 int bestWeight = -1; 5283 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5284 int weight = -1; 5285 unsigned maIndex; 5286 // Compute the sums of the weights for each alternative, keeping track 5287 // of the best (highest weight) one so far. 5288 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5289 int weightSum = 0; 5290 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5291 cIndex != eIndex; ++cIndex) { 5292 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5293 if (OpInfo.Type == InlineAsm::isClobber) 5294 continue; 5295 5296 // If this is an output operand with a matching input operand, 5297 // look up the matching input. If their types mismatch, e.g. one 5298 // is an integer, the other is floating point, or their sizes are 5299 // different, flag it as an maCantMatch. 5300 if (OpInfo.hasMatchingInput()) { 5301 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5302 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5303 if ((OpInfo.ConstraintVT.isInteger() != 5304 Input.ConstraintVT.isInteger()) || 5305 (OpInfo.ConstraintVT.getSizeInBits() != 5306 Input.ConstraintVT.getSizeInBits())) { 5307 weightSum = -1; // Can't match. 5308 break; 5309 } 5310 } 5311 } 5312 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5313 if (weight == -1) { 5314 weightSum = -1; 5315 break; 5316 } 5317 weightSum += weight; 5318 } 5319 // Update best. 5320 if (weightSum > bestWeight) { 5321 bestWeight = weightSum; 5322 bestMAIndex = maIndex; 5323 } 5324 } 5325 5326 // Now select chosen alternative in each constraint. 5327 for (AsmOperandInfo &cInfo : ConstraintOperands) 5328 if (cInfo.Type != InlineAsm::isClobber) 5329 cInfo.selectAlternative(bestMAIndex); 5330 } 5331 } 5332 5333 // Check and hook up tied operands, choose constraint code to use. 5334 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5335 cIndex != eIndex; ++cIndex) { 5336 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5337 5338 // If this is an output operand with a matching input operand, look up the 5339 // matching input. If their types mismatch, e.g. one is an integer, the 5340 // other is floating point, or their sizes are different, flag it as an 5341 // error. 5342 if (OpInfo.hasMatchingInput()) { 5343 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5344 5345 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5346 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5347 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5348 OpInfo.ConstraintVT); 5349 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5350 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5351 Input.ConstraintVT); 5352 if ((OpInfo.ConstraintVT.isInteger() != 5353 Input.ConstraintVT.isInteger()) || 5354 (MatchRC.second != InputRC.second)) { 5355 report_fatal_error("Unsupported asm: input constraint" 5356 " with a matching output constraint of" 5357 " incompatible type!"); 5358 } 5359 } 5360 } 5361 } 5362 5363 return ConstraintOperands; 5364 } 5365 5366 /// Return an integer indicating how general CT is. 5367 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5368 switch (CT) { 5369 case TargetLowering::C_Immediate: 5370 case TargetLowering::C_Other: 5371 case TargetLowering::C_Unknown: 5372 return 0; 5373 case TargetLowering::C_Register: 5374 return 1; 5375 case TargetLowering::C_RegisterClass: 5376 return 2; 5377 case TargetLowering::C_Memory: 5378 case TargetLowering::C_Address: 5379 return 3; 5380 } 5381 llvm_unreachable("Invalid constraint type"); 5382 } 5383 5384 /// Examine constraint type and operand type and determine a weight value. 5385 /// This object must already have been set up with the operand type 5386 /// and the current alternative constraint selected. 5387 TargetLowering::ConstraintWeight 5388 TargetLowering::getMultipleConstraintMatchWeight( 5389 AsmOperandInfo &info, int maIndex) const { 5390 InlineAsm::ConstraintCodeVector *rCodes; 5391 if (maIndex >= (int)info.multipleAlternatives.size()) 5392 rCodes = &info.Codes; 5393 else 5394 rCodes = &info.multipleAlternatives[maIndex].Codes; 5395 ConstraintWeight BestWeight = CW_Invalid; 5396 5397 // Loop over the options, keeping track of the most general one. 5398 for (const std::string &rCode : *rCodes) { 5399 ConstraintWeight weight = 5400 getSingleConstraintMatchWeight(info, rCode.c_str()); 5401 if (weight > BestWeight) 5402 BestWeight = weight; 5403 } 5404 5405 return BestWeight; 5406 } 5407 5408 /// Examine constraint type and operand type and determine a weight value. 5409 /// This object must already have been set up with the operand type 5410 /// and the current alternative constraint selected. 5411 TargetLowering::ConstraintWeight 5412 TargetLowering::getSingleConstraintMatchWeight( 5413 AsmOperandInfo &info, const char *constraint) const { 5414 ConstraintWeight weight = CW_Invalid; 5415 Value *CallOperandVal = info.CallOperandVal; 5416 // If we don't have a value, we can't do a match, 5417 // but allow it at the lowest weight. 5418 if (!CallOperandVal) 5419 return CW_Default; 5420 // Look at the constraint type. 5421 switch (*constraint) { 5422 case 'i': // immediate integer. 5423 case 'n': // immediate integer with a known value. 5424 if (isa<ConstantInt>(CallOperandVal)) 5425 weight = CW_Constant; 5426 break; 5427 case 's': // non-explicit intregal immediate. 5428 if (isa<GlobalValue>(CallOperandVal)) 5429 weight = CW_Constant; 5430 break; 5431 case 'E': // immediate float if host format. 5432 case 'F': // immediate float. 5433 if (isa<ConstantFP>(CallOperandVal)) 5434 weight = CW_Constant; 5435 break; 5436 case '<': // memory operand with autodecrement. 5437 case '>': // memory operand with autoincrement. 5438 case 'm': // memory operand. 5439 case 'o': // offsettable memory operand 5440 case 'V': // non-offsettable memory operand 5441 weight = CW_Memory; 5442 break; 5443 case 'r': // general register. 5444 case 'g': // general register, memory operand or immediate integer. 5445 // note: Clang converts "g" to "imr". 5446 if (CallOperandVal->getType()->isIntegerTy()) 5447 weight = CW_Register; 5448 break; 5449 case 'X': // any operand. 5450 default: 5451 weight = CW_Default; 5452 break; 5453 } 5454 return weight; 5455 } 5456 5457 /// If there are multiple different constraints that we could pick for this 5458 /// operand (e.g. "imr") try to pick the 'best' one. 5459 /// This is somewhat tricky: constraints fall into four classes: 5460 /// Other -> immediates and magic values 5461 /// Register -> one specific register 5462 /// RegisterClass -> a group of regs 5463 /// Memory -> memory 5464 /// Ideally, we would pick the most specific constraint possible: if we have 5465 /// something that fits into a register, we would pick it. The problem here 5466 /// is that if we have something that could either be in a register or in 5467 /// memory that use of the register could cause selection of *other* 5468 /// operands to fail: they might only succeed if we pick memory. Because of 5469 /// this the heuristic we use is: 5470 /// 5471 /// 1) If there is an 'other' constraint, and if the operand is valid for 5472 /// that constraint, use it. This makes us take advantage of 'i' 5473 /// constraints when available. 5474 /// 2) Otherwise, pick the most general constraint present. This prefers 5475 /// 'm' over 'r', for example. 5476 /// 5477 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5478 const TargetLowering &TLI, 5479 SDValue Op, SelectionDAG *DAG) { 5480 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5481 unsigned BestIdx = 0; 5482 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5483 int BestGenerality = -1; 5484 5485 // Loop over the options, keeping track of the most general one. 5486 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5487 TargetLowering::ConstraintType CType = 5488 TLI.getConstraintType(OpInfo.Codes[i]); 5489 5490 // Indirect 'other' or 'immediate' constraints are not allowed. 5491 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5492 CType == TargetLowering::C_Register || 5493 CType == TargetLowering::C_RegisterClass)) 5494 continue; 5495 5496 // If this is an 'other' or 'immediate' constraint, see if the operand is 5497 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5498 // the operand is an integer in the range [0..31] we want to use I (saving a 5499 // load of a register), otherwise we must use 'r'. 5500 if ((CType == TargetLowering::C_Other || 5501 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5502 assert(OpInfo.Codes[i].size() == 1 && 5503 "Unhandled multi-letter 'other' constraint"); 5504 std::vector<SDValue> ResultOps; 5505 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5506 ResultOps, *DAG); 5507 if (!ResultOps.empty()) { 5508 BestType = CType; 5509 BestIdx = i; 5510 break; 5511 } 5512 } 5513 5514 // Things with matching constraints can only be registers, per gcc 5515 // documentation. This mainly affects "g" constraints. 5516 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5517 continue; 5518 5519 // This constraint letter is more general than the previous one, use it. 5520 int Generality = getConstraintGenerality(CType); 5521 if (Generality > BestGenerality) { 5522 BestType = CType; 5523 BestIdx = i; 5524 BestGenerality = Generality; 5525 } 5526 } 5527 5528 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5529 OpInfo.ConstraintType = BestType; 5530 } 5531 5532 /// Determines the constraint code and constraint type to use for the specific 5533 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5534 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5535 SDValue Op, 5536 SelectionDAG *DAG) const { 5537 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5538 5539 // Single-letter constraints ('r') are very common. 5540 if (OpInfo.Codes.size() == 1) { 5541 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5542 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5543 } else { 5544 ChooseConstraint(OpInfo, *this, Op, DAG); 5545 } 5546 5547 // 'X' matches anything. 5548 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5549 // Constants are handled elsewhere. For Functions, the type here is the 5550 // type of the result, which is not what we want to look at; leave them 5551 // alone. 5552 Value *v = OpInfo.CallOperandVal; 5553 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5554 return; 5555 } 5556 5557 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5558 OpInfo.ConstraintCode = "i"; 5559 return; 5560 } 5561 5562 // Otherwise, try to resolve it to something we know about by looking at 5563 // the actual operand type. 5564 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5565 OpInfo.ConstraintCode = Repl; 5566 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5567 } 5568 } 5569 } 5570 5571 /// Given an exact SDIV by a constant, create a multiplication 5572 /// with the multiplicative inverse of the constant. 5573 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5574 const SDLoc &dl, SelectionDAG &DAG, 5575 SmallVectorImpl<SDNode *> &Created) { 5576 SDValue Op0 = N->getOperand(0); 5577 SDValue Op1 = N->getOperand(1); 5578 EVT VT = N->getValueType(0); 5579 EVT SVT = VT.getScalarType(); 5580 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5581 EVT ShSVT = ShVT.getScalarType(); 5582 5583 bool UseSRA = false; 5584 SmallVector<SDValue, 16> Shifts, Factors; 5585 5586 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5587 if (C->isZero()) 5588 return false; 5589 APInt Divisor = C->getAPIntValue(); 5590 unsigned Shift = Divisor.countTrailingZeros(); 5591 if (Shift) { 5592 Divisor.ashrInPlace(Shift); 5593 UseSRA = true; 5594 } 5595 // Calculate the multiplicative inverse, using Newton's method. 5596 APInt t; 5597 APInt Factor = Divisor; 5598 while ((t = Divisor * Factor) != 1) 5599 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5600 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5601 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5602 return true; 5603 }; 5604 5605 // Collect all magic values from the build vector. 5606 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5607 return SDValue(); 5608 5609 SDValue Shift, Factor; 5610 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5611 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5612 Factor = DAG.getBuildVector(VT, dl, Factors); 5613 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5614 assert(Shifts.size() == 1 && Factors.size() == 1 && 5615 "Expected matchUnaryPredicate to return one element for scalable " 5616 "vectors"); 5617 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5618 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5619 } else { 5620 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5621 Shift = Shifts[0]; 5622 Factor = Factors[0]; 5623 } 5624 5625 SDValue Res = Op0; 5626 5627 // Shift the value upfront if it is even, so the LSB is one. 5628 if (UseSRA) { 5629 // TODO: For UDIV use SRL instead of SRA. 5630 SDNodeFlags Flags; 5631 Flags.setExact(true); 5632 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5633 Created.push_back(Res.getNode()); 5634 } 5635 5636 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5637 } 5638 5639 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5640 SelectionDAG &DAG, 5641 SmallVectorImpl<SDNode *> &Created) const { 5642 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5644 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5645 return SDValue(N, 0); // Lower SDIV as SDIV 5646 return SDValue(); 5647 } 5648 5649 SDValue 5650 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5651 SelectionDAG &DAG, 5652 SmallVectorImpl<SDNode *> &Created) const { 5653 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5655 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5656 return SDValue(N, 0); // Lower SREM as SREM 5657 return SDValue(); 5658 } 5659 5660 /// Given an ISD::SDIV node expressing a divide by constant, 5661 /// return a DAG expression to select that will generate the same value by 5662 /// multiplying by a magic number. 5663 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5664 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5665 bool IsAfterLegalization, 5666 SmallVectorImpl<SDNode *> &Created) const { 5667 SDLoc dl(N); 5668 EVT VT = N->getValueType(0); 5669 EVT SVT = VT.getScalarType(); 5670 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5671 EVT ShSVT = ShVT.getScalarType(); 5672 unsigned EltBits = VT.getScalarSizeInBits(); 5673 EVT MulVT; 5674 5675 // Check to see if we can do this. 5676 // FIXME: We should be more aggressive here. 5677 if (!isTypeLegal(VT)) { 5678 // Limit this to simple scalars for now. 5679 if (VT.isVector() || !VT.isSimple()) 5680 return SDValue(); 5681 5682 // If this type will be promoted to a large enough type with a legal 5683 // multiply operation, we can go ahead and do this transform. 5684 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5685 return SDValue(); 5686 5687 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5688 if (MulVT.getSizeInBits() < (2 * EltBits) || 5689 !isOperationLegal(ISD::MUL, MulVT)) 5690 return SDValue(); 5691 } 5692 5693 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5694 if (N->getFlags().hasExact()) 5695 return BuildExactSDIV(*this, N, dl, DAG, Created); 5696 5697 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5698 5699 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5700 if (C->isZero()) 5701 return false; 5702 5703 const APInt &Divisor = C->getAPIntValue(); 5704 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5705 int NumeratorFactor = 0; 5706 int ShiftMask = -1; 5707 5708 if (Divisor.isOne() || Divisor.isAllOnes()) { 5709 // If d is +1/-1, we just multiply the numerator by +1/-1. 5710 NumeratorFactor = Divisor.getSExtValue(); 5711 magics.Magic = 0; 5712 magics.ShiftAmount = 0; 5713 ShiftMask = 0; 5714 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5715 // If d > 0 and m < 0, add the numerator. 5716 NumeratorFactor = 1; 5717 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5718 // If d < 0 and m > 0, subtract the numerator. 5719 NumeratorFactor = -1; 5720 } 5721 5722 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5723 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5724 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5725 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5726 return true; 5727 }; 5728 5729 SDValue N0 = N->getOperand(0); 5730 SDValue N1 = N->getOperand(1); 5731 5732 // Collect the shifts / magic values from each element. 5733 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5734 return SDValue(); 5735 5736 SDValue MagicFactor, Factor, Shift, ShiftMask; 5737 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5738 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5739 Factor = DAG.getBuildVector(VT, dl, Factors); 5740 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5741 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5742 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5743 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5744 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5745 "Expected matchUnaryPredicate to return one element for scalable " 5746 "vectors"); 5747 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5748 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5749 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5750 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5751 } else { 5752 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5753 MagicFactor = MagicFactors[0]; 5754 Factor = Factors[0]; 5755 Shift = Shifts[0]; 5756 ShiftMask = ShiftMasks[0]; 5757 } 5758 5759 // Multiply the numerator (operand 0) by the magic value. 5760 // FIXME: We should support doing a MUL in a wider type. 5761 auto GetMULHS = [&](SDValue X, SDValue Y) { 5762 // If the type isn't legal, use a wider mul of the the type calculated 5763 // earlier. 5764 if (!isTypeLegal(VT)) { 5765 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5766 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5767 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5768 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5769 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5770 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5771 } 5772 5773 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5774 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5775 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5776 SDValue LoHi = 5777 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5778 return SDValue(LoHi.getNode(), 1); 5779 } 5780 return SDValue(); 5781 }; 5782 5783 SDValue Q = GetMULHS(N0, MagicFactor); 5784 if (!Q) 5785 return SDValue(); 5786 5787 Created.push_back(Q.getNode()); 5788 5789 // (Optionally) Add/subtract the numerator using Factor. 5790 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5791 Created.push_back(Factor.getNode()); 5792 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5793 Created.push_back(Q.getNode()); 5794 5795 // Shift right algebraic by shift value. 5796 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5797 Created.push_back(Q.getNode()); 5798 5799 // Extract the sign bit, mask it and add it to the quotient. 5800 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5801 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5802 Created.push_back(T.getNode()); 5803 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5804 Created.push_back(T.getNode()); 5805 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5806 } 5807 5808 /// Given an ISD::UDIV node expressing a divide by constant, 5809 /// return a DAG expression to select that will generate the same value by 5810 /// multiplying by a magic number. 5811 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5812 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5813 bool IsAfterLegalization, 5814 SmallVectorImpl<SDNode *> &Created) const { 5815 SDLoc dl(N); 5816 EVT VT = N->getValueType(0); 5817 EVT SVT = VT.getScalarType(); 5818 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5819 EVT ShSVT = ShVT.getScalarType(); 5820 unsigned EltBits = VT.getScalarSizeInBits(); 5821 EVT MulVT; 5822 5823 // Check to see if we can do this. 5824 // FIXME: We should be more aggressive here. 5825 if (!isTypeLegal(VT)) { 5826 // Limit this to simple scalars for now. 5827 if (VT.isVector() || !VT.isSimple()) 5828 return SDValue(); 5829 5830 // If this type will be promoted to a large enough type with a legal 5831 // multiply operation, we can go ahead and do this transform. 5832 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5833 return SDValue(); 5834 5835 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5836 if (MulVT.getSizeInBits() < (2 * EltBits) || 5837 !isOperationLegal(ISD::MUL, MulVT)) 5838 return SDValue(); 5839 } 5840 5841 bool UseNPQ = false; 5842 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5843 5844 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5845 if (C->isZero()) 5846 return false; 5847 // FIXME: We should use a narrower constant when the upper 5848 // bits are known to be zero. 5849 const APInt& Divisor = C->getAPIntValue(); 5850 UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor); 5851 unsigned PreShift = 0, PostShift = 0; 5852 5853 // If the divisor is even, we can avoid using the expensive fixup by 5854 // shifting the divided value upfront. 5855 if (magics.IsAdd != 0 && !Divisor[0]) { 5856 PreShift = Divisor.countTrailingZeros(); 5857 // Get magic number for the shifted divisor. 5858 magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5859 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 5860 } 5861 5862 APInt Magic = magics.Magic; 5863 5864 unsigned SelNPQ; 5865 if (magics.IsAdd == 0 || Divisor.isOne()) { 5866 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5867 "We shouldn't generate an undefined shift!"); 5868 PostShift = magics.ShiftAmount; 5869 SelNPQ = false; 5870 } else { 5871 PostShift = magics.ShiftAmount - 1; 5872 SelNPQ = true; 5873 } 5874 5875 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5876 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5877 NPQFactors.push_back( 5878 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5879 : APInt::getZero(EltBits), 5880 dl, SVT)); 5881 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5882 UseNPQ |= SelNPQ; 5883 return true; 5884 }; 5885 5886 SDValue N0 = N->getOperand(0); 5887 SDValue N1 = N->getOperand(1); 5888 5889 // Collect the shifts/magic values from each element. 5890 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5891 return SDValue(); 5892 5893 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5894 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5895 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5896 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5897 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5898 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5899 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5900 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5901 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5902 "Expected matchUnaryPredicate to return one for scalable vectors"); 5903 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5904 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5905 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5906 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5907 } else { 5908 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5909 PreShift = PreShifts[0]; 5910 MagicFactor = MagicFactors[0]; 5911 PostShift = PostShifts[0]; 5912 } 5913 5914 SDValue Q = N0; 5915 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5916 Created.push_back(Q.getNode()); 5917 5918 // FIXME: We should support doing a MUL in a wider type. 5919 auto GetMULHU = [&](SDValue X, SDValue Y) { 5920 // If the type isn't legal, use a wider mul of the the type calculated 5921 // earlier. 5922 if (!isTypeLegal(VT)) { 5923 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5924 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5925 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5926 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5927 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5928 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5929 } 5930 5931 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5932 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5933 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5934 SDValue LoHi = 5935 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5936 return SDValue(LoHi.getNode(), 1); 5937 } 5938 return SDValue(); // No mulhu or equivalent 5939 }; 5940 5941 // Multiply the numerator (operand 0) by the magic value. 5942 Q = GetMULHU(Q, MagicFactor); 5943 if (!Q) 5944 return SDValue(); 5945 5946 Created.push_back(Q.getNode()); 5947 5948 if (UseNPQ) { 5949 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5950 Created.push_back(NPQ.getNode()); 5951 5952 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5953 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5954 if (VT.isVector()) 5955 NPQ = GetMULHU(NPQ, NPQFactor); 5956 else 5957 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5958 5959 Created.push_back(NPQ.getNode()); 5960 5961 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5962 Created.push_back(Q.getNode()); 5963 } 5964 5965 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5966 Created.push_back(Q.getNode()); 5967 5968 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5969 5970 SDValue One = DAG.getConstant(1, dl, VT); 5971 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5972 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5973 } 5974 5975 /// If all values in Values that *don't* match the predicate are same 'splat' 5976 /// value, then replace all values with that splat value. 5977 /// Else, if AlternativeReplacement was provided, then replace all values that 5978 /// do match predicate with AlternativeReplacement value. 5979 static void 5980 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5981 std::function<bool(SDValue)> Predicate, 5982 SDValue AlternativeReplacement = SDValue()) { 5983 SDValue Replacement; 5984 // Is there a value for which the Predicate does *NOT* match? What is it? 5985 auto SplatValue = llvm::find_if_not(Values, Predicate); 5986 if (SplatValue != Values.end()) { 5987 // Does Values consist only of SplatValue's and values matching Predicate? 5988 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5989 return Value == *SplatValue || Predicate(Value); 5990 })) // Then we shall replace values matching predicate with SplatValue. 5991 Replacement = *SplatValue; 5992 } 5993 if (!Replacement) { 5994 // Oops, we did not find the "baseline" splat value. 5995 if (!AlternativeReplacement) 5996 return; // Nothing to do. 5997 // Let's replace with provided value then. 5998 Replacement = AlternativeReplacement; 5999 } 6000 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6001 } 6002 6003 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6004 /// where the divisor is constant and the comparison target is zero, 6005 /// return a DAG expression that will generate the same comparison result 6006 /// using only multiplications, additions and shifts/rotations. 6007 /// Ref: "Hacker's Delight" 10-17. 6008 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6009 SDValue CompTargetNode, 6010 ISD::CondCode Cond, 6011 DAGCombinerInfo &DCI, 6012 const SDLoc &DL) const { 6013 SmallVector<SDNode *, 5> Built; 6014 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6015 DCI, DL, Built)) { 6016 for (SDNode *N : Built) 6017 DCI.AddToWorklist(N); 6018 return Folded; 6019 } 6020 6021 return SDValue(); 6022 } 6023 6024 SDValue 6025 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6026 SDValue CompTargetNode, ISD::CondCode Cond, 6027 DAGCombinerInfo &DCI, const SDLoc &DL, 6028 SmallVectorImpl<SDNode *> &Created) const { 6029 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6030 // - D must be constant, with D = D0 * 2^K where D0 is odd 6031 // - P is the multiplicative inverse of D0 modulo 2^W 6032 // - Q = floor(((2^W) - 1) / D) 6033 // where W is the width of the common type of N and D. 6034 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6035 "Only applicable for (in)equality comparisons."); 6036 6037 SelectionDAG &DAG = DCI.DAG; 6038 6039 EVT VT = REMNode.getValueType(); 6040 EVT SVT = VT.getScalarType(); 6041 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6042 EVT ShSVT = ShVT.getScalarType(); 6043 6044 // If MUL is unavailable, we cannot proceed in any case. 6045 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6046 return SDValue(); 6047 6048 bool ComparingWithAllZeros = true; 6049 bool AllComparisonsWithNonZerosAreTautological = true; 6050 bool HadTautologicalLanes = false; 6051 bool AllLanesAreTautological = true; 6052 bool HadEvenDivisor = false; 6053 bool AllDivisorsArePowerOfTwo = true; 6054 bool HadTautologicalInvertedLanes = false; 6055 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6056 6057 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6058 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6059 if (CDiv->isZero()) 6060 return false; 6061 6062 const APInt &D = CDiv->getAPIntValue(); 6063 const APInt &Cmp = CCmp->getAPIntValue(); 6064 6065 ComparingWithAllZeros &= Cmp.isZero(); 6066 6067 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6068 // if C2 is not less than C1, the comparison is always false. 6069 // But we will only be able to produce the comparison that will give the 6070 // opposive tautological answer. So this lane would need to be fixed up. 6071 bool TautologicalInvertedLane = D.ule(Cmp); 6072 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6073 6074 // If all lanes are tautological (either all divisors are ones, or divisor 6075 // is not greater than the constant we are comparing with), 6076 // we will prefer to avoid the fold. 6077 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6078 HadTautologicalLanes |= TautologicalLane; 6079 AllLanesAreTautological &= TautologicalLane; 6080 6081 // If we are comparing with non-zero, we need'll need to subtract said 6082 // comparison value from the LHS. But there is no point in doing that if 6083 // every lane where we are comparing with non-zero is tautological.. 6084 if (!Cmp.isZero()) 6085 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6086 6087 // Decompose D into D0 * 2^K 6088 unsigned K = D.countTrailingZeros(); 6089 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6090 APInt D0 = D.lshr(K); 6091 6092 // D is even if it has trailing zeros. 6093 HadEvenDivisor |= (K != 0); 6094 // D is a power-of-two if D0 is one. 6095 // If all divisors are power-of-two, we will prefer to avoid the fold. 6096 AllDivisorsArePowerOfTwo &= D0.isOne(); 6097 6098 // P = inv(D0, 2^W) 6099 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6100 unsigned W = D.getBitWidth(); 6101 APInt P = D0.zext(W + 1) 6102 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6103 .trunc(W); 6104 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6105 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6106 6107 // Q = floor((2^W - 1) u/ D) 6108 // R = ((2^W - 1) u% D) 6109 APInt Q, R; 6110 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6111 6112 // If we are comparing with zero, then that comparison constant is okay, 6113 // else it may need to be one less than that. 6114 if (Cmp.ugt(R)) 6115 Q -= 1; 6116 6117 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6118 "We are expecting that K is always less than all-ones for ShSVT"); 6119 6120 // If the lane is tautological the result can be constant-folded. 6121 if (TautologicalLane) { 6122 // Set P and K amount to a bogus values so we can try to splat them. 6123 P = 0; 6124 K = -1; 6125 // And ensure that comparison constant is tautological, 6126 // it will always compare true/false. 6127 Q = -1; 6128 } 6129 6130 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6131 KAmts.push_back( 6132 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6133 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6134 return true; 6135 }; 6136 6137 SDValue N = REMNode.getOperand(0); 6138 SDValue D = REMNode.getOperand(1); 6139 6140 // Collect the values from each element. 6141 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6142 return SDValue(); 6143 6144 // If all lanes are tautological, the result can be constant-folded. 6145 if (AllLanesAreTautological) 6146 return SDValue(); 6147 6148 // If this is a urem by a powers-of-two, avoid the fold since it can be 6149 // best implemented as a bit test. 6150 if (AllDivisorsArePowerOfTwo) 6151 return SDValue(); 6152 6153 SDValue PVal, KVal, QVal; 6154 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6155 if (HadTautologicalLanes) { 6156 // Try to turn PAmts into a splat, since we don't care about the values 6157 // that are currently '0'. If we can't, just keep '0'`s. 6158 turnVectorIntoSplatVector(PAmts, isNullConstant); 6159 // Try to turn KAmts into a splat, since we don't care about the values 6160 // that are currently '-1'. If we can't, change them to '0'`s. 6161 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6162 DAG.getConstant(0, DL, ShSVT)); 6163 } 6164 6165 PVal = DAG.getBuildVector(VT, DL, PAmts); 6166 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6167 QVal = DAG.getBuildVector(VT, DL, QAmts); 6168 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6169 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6170 "Expected matchBinaryPredicate to return one element for " 6171 "SPLAT_VECTORs"); 6172 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6173 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6174 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6175 } else { 6176 PVal = PAmts[0]; 6177 KVal = KAmts[0]; 6178 QVal = QAmts[0]; 6179 } 6180 6181 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6182 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6183 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6184 assert(CompTargetNode.getValueType() == N.getValueType() && 6185 "Expecting that the types on LHS and RHS of comparisons match."); 6186 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6187 } 6188 6189 // (mul N, P) 6190 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6191 Created.push_back(Op0.getNode()); 6192 6193 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6194 // divisors as a performance improvement, since rotating by 0 is a no-op. 6195 if (HadEvenDivisor) { 6196 // We need ROTR to do this. 6197 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6198 return SDValue(); 6199 // UREM: (rotr (mul N, P), K) 6200 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6201 Created.push_back(Op0.getNode()); 6202 } 6203 6204 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6205 SDValue NewCC = 6206 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6207 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6208 if (!HadTautologicalInvertedLanes) 6209 return NewCC; 6210 6211 // If any lanes previously compared always-false, the NewCC will give 6212 // always-true result for them, so we need to fixup those lanes. 6213 // Or the other way around for inequality predicate. 6214 assert(VT.isVector() && "Can/should only get here for vectors."); 6215 Created.push_back(NewCC.getNode()); 6216 6217 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6218 // if C2 is not less than C1, the comparison is always false. 6219 // But we have produced the comparison that will give the 6220 // opposive tautological answer. So these lanes would need to be fixed up. 6221 SDValue TautologicalInvertedChannels = 6222 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6223 Created.push_back(TautologicalInvertedChannels.getNode()); 6224 6225 // NOTE: we avoid letting illegal types through even if we're before legalize 6226 // ops – legalization has a hard time producing good code for this. 6227 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6228 // If we have a vector select, let's replace the comparison results in the 6229 // affected lanes with the correct tautological result. 6230 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6231 DL, SETCCVT, SETCCVT); 6232 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6233 Replacement, NewCC); 6234 } 6235 6236 // Else, we can just invert the comparison result in the appropriate lanes. 6237 // 6238 // NOTE: see the note above VSELECT above. 6239 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6240 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6241 TautologicalInvertedChannels); 6242 6243 return SDValue(); // Don't know how to lower. 6244 } 6245 6246 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6247 /// where the divisor is constant and the comparison target is zero, 6248 /// return a DAG expression that will generate the same comparison result 6249 /// using only multiplications, additions and shifts/rotations. 6250 /// Ref: "Hacker's Delight" 10-17. 6251 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6252 SDValue CompTargetNode, 6253 ISD::CondCode Cond, 6254 DAGCombinerInfo &DCI, 6255 const SDLoc &DL) const { 6256 SmallVector<SDNode *, 7> Built; 6257 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6258 DCI, DL, Built)) { 6259 assert(Built.size() <= 7 && "Max size prediction failed."); 6260 for (SDNode *N : Built) 6261 DCI.AddToWorklist(N); 6262 return Folded; 6263 } 6264 6265 return SDValue(); 6266 } 6267 6268 SDValue 6269 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6270 SDValue CompTargetNode, ISD::CondCode Cond, 6271 DAGCombinerInfo &DCI, const SDLoc &DL, 6272 SmallVectorImpl<SDNode *> &Created) const { 6273 // Fold: 6274 // (seteq/ne (srem N, D), 0) 6275 // To: 6276 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6277 // 6278 // - D must be constant, with D = D0 * 2^K where D0 is odd 6279 // - P is the multiplicative inverse of D0 modulo 2^W 6280 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6281 // - Q = floor((2 * A) / (2^K)) 6282 // where W is the width of the common type of N and D. 6283 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6284 "Only applicable for (in)equality comparisons."); 6285 6286 SelectionDAG &DAG = DCI.DAG; 6287 6288 EVT VT = REMNode.getValueType(); 6289 EVT SVT = VT.getScalarType(); 6290 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6291 EVT ShSVT = ShVT.getScalarType(); 6292 6293 // If we are after ops legalization, and MUL is unavailable, we can not 6294 // proceed. 6295 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6296 return SDValue(); 6297 6298 // TODO: Could support comparing with non-zero too. 6299 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6300 if (!CompTarget || !CompTarget->isZero()) 6301 return SDValue(); 6302 6303 bool HadIntMinDivisor = false; 6304 bool HadOneDivisor = false; 6305 bool AllDivisorsAreOnes = true; 6306 bool HadEvenDivisor = false; 6307 bool NeedToApplyOffset = false; 6308 bool AllDivisorsArePowerOfTwo = true; 6309 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6310 6311 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6312 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6313 if (C->isZero()) 6314 return false; 6315 6316 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6317 6318 // WARNING: this fold is only valid for positive divisors! 6319 APInt D = C->getAPIntValue(); 6320 if (D.isNegative()) 6321 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6322 6323 HadIntMinDivisor |= D.isMinSignedValue(); 6324 6325 // If all divisors are ones, we will prefer to avoid the fold. 6326 HadOneDivisor |= D.isOne(); 6327 AllDivisorsAreOnes &= D.isOne(); 6328 6329 // Decompose D into D0 * 2^K 6330 unsigned K = D.countTrailingZeros(); 6331 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6332 APInt D0 = D.lshr(K); 6333 6334 if (!D.isMinSignedValue()) { 6335 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6336 // we don't care about this lane in this fold, we'll special-handle it. 6337 HadEvenDivisor |= (K != 0); 6338 } 6339 6340 // D is a power-of-two if D0 is one. This includes INT_MIN. 6341 // If all divisors are power-of-two, we will prefer to avoid the fold. 6342 AllDivisorsArePowerOfTwo &= D0.isOne(); 6343 6344 // P = inv(D0, 2^W) 6345 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6346 unsigned W = D.getBitWidth(); 6347 APInt P = D0.zext(W + 1) 6348 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6349 .trunc(W); 6350 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6351 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6352 6353 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6354 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6355 A.clearLowBits(K); 6356 6357 if (!D.isMinSignedValue()) { 6358 // If divisor INT_MIN, then we don't care about this lane in this fold, 6359 // we'll special-handle it. 6360 NeedToApplyOffset |= A != 0; 6361 } 6362 6363 // Q = floor((2 * A) / (2^K)) 6364 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6365 6366 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6367 "We are expecting that A is always less than all-ones for SVT"); 6368 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6369 "We are expecting that K is always less than all-ones for ShSVT"); 6370 6371 // If the divisor is 1 the result can be constant-folded. Likewise, we 6372 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6373 if (D.isOne()) { 6374 // Set P, A and K to a bogus values so we can try to splat them. 6375 P = 0; 6376 A = -1; 6377 K = -1; 6378 6379 // x ?% 1 == 0 <--> true <--> x u<= -1 6380 Q = -1; 6381 } 6382 6383 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6384 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6385 KAmts.push_back( 6386 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6387 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6388 return true; 6389 }; 6390 6391 SDValue N = REMNode.getOperand(0); 6392 SDValue D = REMNode.getOperand(1); 6393 6394 // Collect the values from each element. 6395 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6396 return SDValue(); 6397 6398 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6399 if (AllDivisorsAreOnes) 6400 return SDValue(); 6401 6402 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6403 // since it can be best implemented as a bit test. 6404 if (AllDivisorsArePowerOfTwo) 6405 return SDValue(); 6406 6407 SDValue PVal, AVal, KVal, QVal; 6408 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6409 if (HadOneDivisor) { 6410 // Try to turn PAmts into a splat, since we don't care about the values 6411 // that are currently '0'. If we can't, just keep '0'`s. 6412 turnVectorIntoSplatVector(PAmts, isNullConstant); 6413 // Try to turn AAmts into a splat, since we don't care about the 6414 // values that are currently '-1'. If we can't, change them to '0'`s. 6415 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6416 DAG.getConstant(0, DL, SVT)); 6417 // Try to turn KAmts into a splat, since we don't care about the values 6418 // that are currently '-1'. If we can't, change them to '0'`s. 6419 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6420 DAG.getConstant(0, DL, ShSVT)); 6421 } 6422 6423 PVal = DAG.getBuildVector(VT, DL, PAmts); 6424 AVal = DAG.getBuildVector(VT, DL, AAmts); 6425 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6426 QVal = DAG.getBuildVector(VT, DL, QAmts); 6427 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6428 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6429 QAmts.size() == 1 && 6430 "Expected matchUnaryPredicate to return one element for scalable " 6431 "vectors"); 6432 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6433 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6434 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6435 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6436 } else { 6437 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6438 PVal = PAmts[0]; 6439 AVal = AAmts[0]; 6440 KVal = KAmts[0]; 6441 QVal = QAmts[0]; 6442 } 6443 6444 // (mul N, P) 6445 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6446 Created.push_back(Op0.getNode()); 6447 6448 if (NeedToApplyOffset) { 6449 // We need ADD to do this. 6450 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6451 return SDValue(); 6452 6453 // (add (mul N, P), A) 6454 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6455 Created.push_back(Op0.getNode()); 6456 } 6457 6458 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6459 // divisors as a performance improvement, since rotating by 0 is a no-op. 6460 if (HadEvenDivisor) { 6461 // We need ROTR to do this. 6462 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6463 return SDValue(); 6464 // SREM: (rotr (add (mul N, P), A), K) 6465 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6466 Created.push_back(Op0.getNode()); 6467 } 6468 6469 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6470 SDValue Fold = 6471 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6472 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6473 6474 // If we didn't have lanes with INT_MIN divisor, then we're done. 6475 if (!HadIntMinDivisor) 6476 return Fold; 6477 6478 // That fold is only valid for positive divisors. Which effectively means, 6479 // it is invalid for INT_MIN divisors. So if we have such a lane, 6480 // we must fix-up results for said lanes. 6481 assert(VT.isVector() && "Can/should only get here for vectors."); 6482 6483 // NOTE: we avoid letting illegal types through even if we're before legalize 6484 // ops – legalization has a hard time producing good code for the code that 6485 // follows. 6486 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6487 !isOperationLegalOrCustom(ISD::AND, VT) || 6488 !isOperationLegalOrCustom(Cond, VT) || 6489 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6490 return SDValue(); 6491 6492 Created.push_back(Fold.getNode()); 6493 6494 SDValue IntMin = DAG.getConstant( 6495 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6496 SDValue IntMax = DAG.getConstant( 6497 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6498 SDValue Zero = 6499 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6500 6501 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6502 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6503 Created.push_back(DivisorIsIntMin.getNode()); 6504 6505 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6506 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6507 Created.push_back(Masked.getNode()); 6508 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6509 Created.push_back(MaskedIsZero.getNode()); 6510 6511 // To produce final result we need to blend 2 vectors: 'SetCC' and 6512 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6513 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6514 // constant-folded, select can get lowered to a shuffle with constant mask. 6515 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6516 MaskedIsZero, Fold); 6517 6518 return Blended; 6519 } 6520 6521 bool TargetLowering:: 6522 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6523 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6524 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6525 "be a constant integer"); 6526 return true; 6527 } 6528 6529 return false; 6530 } 6531 6532 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6533 const DenormalMode &Mode) const { 6534 SDLoc DL(Op); 6535 EVT VT = Op.getValueType(); 6536 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6537 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6538 // Testing it with denormal inputs to avoid wrong estimate. 6539 if (Mode.Input == DenormalMode::IEEE) { 6540 // This is specifically a check for the handling of denormal inputs, 6541 // not the result. 6542 6543 // Test = fabs(X) < SmallestNormal 6544 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6545 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6546 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6547 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6548 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6549 } 6550 // Test = X == 0.0 6551 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6552 } 6553 6554 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6555 bool LegalOps, bool OptForSize, 6556 NegatibleCost &Cost, 6557 unsigned Depth) const { 6558 // fneg is removable even if it has multiple uses. 6559 if (Op.getOpcode() == ISD::FNEG) { 6560 Cost = NegatibleCost::Cheaper; 6561 return Op.getOperand(0); 6562 } 6563 6564 // Don't recurse exponentially. 6565 if (Depth > SelectionDAG::MaxRecursionDepth) 6566 return SDValue(); 6567 6568 // Pre-increment recursion depth for use in recursive calls. 6569 ++Depth; 6570 const SDNodeFlags Flags = Op->getFlags(); 6571 const TargetOptions &Options = DAG.getTarget().Options; 6572 EVT VT = Op.getValueType(); 6573 unsigned Opcode = Op.getOpcode(); 6574 6575 // Don't allow anything with multiple uses unless we know it is free. 6576 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6577 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6578 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6579 if (!IsFreeExtend) 6580 return SDValue(); 6581 } 6582 6583 auto RemoveDeadNode = [&](SDValue N) { 6584 if (N && N.getNode()->use_empty()) 6585 DAG.RemoveDeadNode(N.getNode()); 6586 }; 6587 6588 SDLoc DL(Op); 6589 6590 // Because getNegatedExpression can delete nodes we need a handle to keep 6591 // temporary nodes alive in case the recursion manages to create an identical 6592 // node. 6593 std::list<HandleSDNode> Handles; 6594 6595 switch (Opcode) { 6596 case ISD::ConstantFP: { 6597 // Don't invert constant FP values after legalization unless the target says 6598 // the negated constant is legal. 6599 bool IsOpLegal = 6600 isOperationLegal(ISD::ConstantFP, VT) || 6601 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6602 OptForSize); 6603 6604 if (LegalOps && !IsOpLegal) 6605 break; 6606 6607 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6608 V.changeSign(); 6609 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6610 6611 // If we already have the use of the negated floating constant, it is free 6612 // to negate it even it has multiple uses. 6613 if (!Op.hasOneUse() && CFP.use_empty()) 6614 break; 6615 Cost = NegatibleCost::Neutral; 6616 return CFP; 6617 } 6618 case ISD::BUILD_VECTOR: { 6619 // Only permit BUILD_VECTOR of constants. 6620 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6621 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6622 })) 6623 break; 6624 6625 bool IsOpLegal = 6626 (isOperationLegal(ISD::ConstantFP, VT) && 6627 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6628 llvm::all_of(Op->op_values(), [&](SDValue N) { 6629 return N.isUndef() || 6630 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6631 OptForSize); 6632 }); 6633 6634 if (LegalOps && !IsOpLegal) 6635 break; 6636 6637 SmallVector<SDValue, 4> Ops; 6638 for (SDValue C : Op->op_values()) { 6639 if (C.isUndef()) { 6640 Ops.push_back(C); 6641 continue; 6642 } 6643 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6644 V.changeSign(); 6645 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6646 } 6647 Cost = NegatibleCost::Neutral; 6648 return DAG.getBuildVector(VT, DL, Ops); 6649 } 6650 case ISD::FADD: { 6651 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6652 break; 6653 6654 // After operation legalization, it might not be legal to create new FSUBs. 6655 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6656 break; 6657 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6658 6659 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6660 NegatibleCost CostX = NegatibleCost::Expensive; 6661 SDValue NegX = 6662 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6663 // Prevent this node from being deleted by the next call. 6664 if (NegX) 6665 Handles.emplace_back(NegX); 6666 6667 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6668 NegatibleCost CostY = NegatibleCost::Expensive; 6669 SDValue NegY = 6670 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6671 6672 // We're done with the handles. 6673 Handles.clear(); 6674 6675 // Negate the X if its cost is less or equal than Y. 6676 if (NegX && (CostX <= CostY)) { 6677 Cost = CostX; 6678 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6679 if (NegY != N) 6680 RemoveDeadNode(NegY); 6681 return N; 6682 } 6683 6684 // Negate the Y if it is not expensive. 6685 if (NegY) { 6686 Cost = CostY; 6687 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6688 if (NegX != N) 6689 RemoveDeadNode(NegX); 6690 return N; 6691 } 6692 break; 6693 } 6694 case ISD::FSUB: { 6695 // We can't turn -(A-B) into B-A when we honor signed zeros. 6696 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6697 break; 6698 6699 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6700 // fold (fneg (fsub 0, Y)) -> Y 6701 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6702 if (C->isZero()) { 6703 Cost = NegatibleCost::Cheaper; 6704 return Y; 6705 } 6706 6707 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6708 Cost = NegatibleCost::Neutral; 6709 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6710 } 6711 case ISD::FMUL: 6712 case ISD::FDIV: { 6713 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6714 6715 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6716 NegatibleCost CostX = NegatibleCost::Expensive; 6717 SDValue NegX = 6718 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6719 // Prevent this node from being deleted by the next call. 6720 if (NegX) 6721 Handles.emplace_back(NegX); 6722 6723 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6724 NegatibleCost CostY = NegatibleCost::Expensive; 6725 SDValue NegY = 6726 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6727 6728 // We're done with the handles. 6729 Handles.clear(); 6730 6731 // Negate the X if its cost is less or equal than Y. 6732 if (NegX && (CostX <= CostY)) { 6733 Cost = CostX; 6734 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6735 if (NegY != N) 6736 RemoveDeadNode(NegY); 6737 return N; 6738 } 6739 6740 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6741 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6742 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6743 break; 6744 6745 // Negate the Y if it is not expensive. 6746 if (NegY) { 6747 Cost = CostY; 6748 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6749 if (NegX != N) 6750 RemoveDeadNode(NegX); 6751 return N; 6752 } 6753 break; 6754 } 6755 case ISD::FMA: 6756 case ISD::FMAD: { 6757 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6758 break; 6759 6760 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6761 NegatibleCost CostZ = NegatibleCost::Expensive; 6762 SDValue NegZ = 6763 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6764 // Give up if fail to negate the Z. 6765 if (!NegZ) 6766 break; 6767 6768 // Prevent this node from being deleted by the next two calls. 6769 Handles.emplace_back(NegZ); 6770 6771 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6772 NegatibleCost CostX = NegatibleCost::Expensive; 6773 SDValue NegX = 6774 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6775 // Prevent this node from being deleted by the next call. 6776 if (NegX) 6777 Handles.emplace_back(NegX); 6778 6779 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6780 NegatibleCost CostY = NegatibleCost::Expensive; 6781 SDValue NegY = 6782 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6783 6784 // We're done with the handles. 6785 Handles.clear(); 6786 6787 // Negate the X if its cost is less or equal than Y. 6788 if (NegX && (CostX <= CostY)) { 6789 Cost = std::min(CostX, CostZ); 6790 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6791 if (NegY != N) 6792 RemoveDeadNode(NegY); 6793 return N; 6794 } 6795 6796 // Negate the Y if it is not expensive. 6797 if (NegY) { 6798 Cost = std::min(CostY, CostZ); 6799 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6800 if (NegX != N) 6801 RemoveDeadNode(NegX); 6802 return N; 6803 } 6804 break; 6805 } 6806 6807 case ISD::FP_EXTEND: 6808 case ISD::FSIN: 6809 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6810 OptForSize, Cost, Depth)) 6811 return DAG.getNode(Opcode, DL, VT, NegV); 6812 break; 6813 case ISD::FP_ROUND: 6814 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6815 OptForSize, Cost, Depth)) 6816 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6817 break; 6818 } 6819 6820 return SDValue(); 6821 } 6822 6823 //===----------------------------------------------------------------------===// 6824 // Legalization Utilities 6825 //===----------------------------------------------------------------------===// 6826 6827 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6828 SDValue LHS, SDValue RHS, 6829 SmallVectorImpl<SDValue> &Result, 6830 EVT HiLoVT, SelectionDAG &DAG, 6831 MulExpansionKind Kind, SDValue LL, 6832 SDValue LH, SDValue RL, SDValue RH) const { 6833 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6834 Opcode == ISD::SMUL_LOHI); 6835 6836 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6837 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6838 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6839 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6840 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6841 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6842 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6843 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6844 6845 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6846 return false; 6847 6848 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6849 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6850 6851 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6852 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6853 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6854 6855 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6856 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6857 bool Signed) -> bool { 6858 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6859 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6860 Hi = SDValue(Lo.getNode(), 1); 6861 return true; 6862 } 6863 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6864 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6865 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6866 return true; 6867 } 6868 return false; 6869 }; 6870 6871 SDValue Lo, Hi; 6872 6873 if (!LL.getNode() && !RL.getNode() && 6874 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6875 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6876 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6877 } 6878 6879 if (!LL.getNode()) 6880 return false; 6881 6882 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6883 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6884 DAG.MaskedValueIsZero(RHS, HighMask)) { 6885 // The inputs are both zero-extended. 6886 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6887 Result.push_back(Lo); 6888 Result.push_back(Hi); 6889 if (Opcode != ISD::MUL) { 6890 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6891 Result.push_back(Zero); 6892 Result.push_back(Zero); 6893 } 6894 return true; 6895 } 6896 } 6897 6898 if (!VT.isVector() && Opcode == ISD::MUL && 6899 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6900 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6901 // The input values are both sign-extended. 6902 // TODO non-MUL case? 6903 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6904 Result.push_back(Lo); 6905 Result.push_back(Hi); 6906 return true; 6907 } 6908 } 6909 6910 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6911 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6912 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6913 6914 if (!LH.getNode() && !RH.getNode() && 6915 isOperationLegalOrCustom(ISD::SRL, VT) && 6916 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6917 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6918 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6919 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6920 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6921 } 6922 6923 if (!LH.getNode()) 6924 return false; 6925 6926 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6927 return false; 6928 6929 Result.push_back(Lo); 6930 6931 if (Opcode == ISD::MUL) { 6932 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6933 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6934 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6935 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6936 Result.push_back(Hi); 6937 return true; 6938 } 6939 6940 // Compute the full width result. 6941 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6942 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6943 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6944 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6945 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6946 }; 6947 6948 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6949 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6950 return false; 6951 6952 // This is effectively the add part of a multiply-add of half-sized operands, 6953 // so it cannot overflow. 6954 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6955 6956 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6957 return false; 6958 6959 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6960 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6961 6962 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6963 isOperationLegalOrCustom(ISD::ADDE, VT)); 6964 if (UseGlue) 6965 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6966 Merge(Lo, Hi)); 6967 else 6968 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6969 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6970 6971 SDValue Carry = Next.getValue(1); 6972 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6973 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6974 6975 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6976 return false; 6977 6978 if (UseGlue) 6979 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6980 Carry); 6981 else 6982 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6983 Zero, Carry); 6984 6985 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6986 6987 if (Opcode == ISD::SMUL_LOHI) { 6988 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6989 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6990 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6991 6992 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6993 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6994 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6995 } 6996 6997 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6998 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6999 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7000 return true; 7001 } 7002 7003 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7004 SelectionDAG &DAG, MulExpansionKind Kind, 7005 SDValue LL, SDValue LH, SDValue RL, 7006 SDValue RH) const { 7007 SmallVector<SDValue, 2> Result; 7008 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7009 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7010 DAG, Kind, LL, LH, RL, RH); 7011 if (Ok) { 7012 assert(Result.size() == 2); 7013 Lo = Result[0]; 7014 Hi = Result[1]; 7015 } 7016 return Ok; 7017 } 7018 7019 // Check that (every element of) Z is undef or not an exact multiple of BW. 7020 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7021 return ISD::matchUnaryPredicate( 7022 Z, 7023 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7024 true); 7025 } 7026 7027 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7028 SelectionDAG &DAG) const { 7029 EVT VT = Node->getValueType(0); 7030 7031 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7032 !isOperationLegalOrCustom(ISD::SRL, VT) || 7033 !isOperationLegalOrCustom(ISD::SUB, VT) || 7034 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7035 return SDValue(); 7036 7037 SDValue X = Node->getOperand(0); 7038 SDValue Y = Node->getOperand(1); 7039 SDValue Z = Node->getOperand(2); 7040 7041 unsigned BW = VT.getScalarSizeInBits(); 7042 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7043 SDLoc DL(SDValue(Node, 0)); 7044 7045 EVT ShVT = Z.getValueType(); 7046 7047 // If a funnel shift in the other direction is more supported, use it. 7048 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7049 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7050 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7051 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7052 // fshl X, Y, Z -> fshr X, Y, -Z 7053 // fshr X, Y, Z -> fshl X, Y, -Z 7054 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7055 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7056 } else { 7057 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7058 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7059 SDValue One = DAG.getConstant(1, DL, ShVT); 7060 if (IsFSHL) { 7061 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7062 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7063 } else { 7064 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7065 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7066 } 7067 Z = DAG.getNOT(DL, Z, ShVT); 7068 } 7069 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7070 } 7071 7072 SDValue ShX, ShY; 7073 SDValue ShAmt, InvShAmt; 7074 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7075 // fshl: X << C | Y >> (BW - C) 7076 // fshr: X << (BW - C) | Y >> C 7077 // where C = Z % BW is not zero 7078 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7079 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7080 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7081 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7082 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7083 } else { 7084 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7085 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7086 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7087 if (isPowerOf2_32(BW)) { 7088 // Z % BW -> Z & (BW - 1) 7089 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7090 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7091 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7092 } else { 7093 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7094 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7095 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7096 } 7097 7098 SDValue One = DAG.getConstant(1, DL, ShVT); 7099 if (IsFSHL) { 7100 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7101 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7102 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7103 } else { 7104 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7105 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7106 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7107 } 7108 } 7109 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7110 } 7111 7112 // TODO: Merge with expandFunnelShift. 7113 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7114 SelectionDAG &DAG) const { 7115 EVT VT = Node->getValueType(0); 7116 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7117 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7118 SDValue Op0 = Node->getOperand(0); 7119 SDValue Op1 = Node->getOperand(1); 7120 SDLoc DL(SDValue(Node, 0)); 7121 7122 EVT ShVT = Op1.getValueType(); 7123 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7124 7125 // If a rotate in the other direction is more supported, use it. 7126 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7127 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7128 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7129 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7130 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7131 } 7132 7133 if (!AllowVectorOps && VT.isVector() && 7134 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7135 !isOperationLegalOrCustom(ISD::SRL, VT) || 7136 !isOperationLegalOrCustom(ISD::SUB, VT) || 7137 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7138 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7139 return SDValue(); 7140 7141 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7142 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7143 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7144 SDValue ShVal; 7145 SDValue HsVal; 7146 if (isPowerOf2_32(EltSizeInBits)) { 7147 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7148 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7149 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7150 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7151 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7152 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7153 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7154 } else { 7155 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7156 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7157 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7158 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7159 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7160 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7161 SDValue One = DAG.getConstant(1, DL, ShVT); 7162 HsVal = 7163 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7164 } 7165 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7166 } 7167 7168 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7169 SelectionDAG &DAG) const { 7170 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7171 EVT VT = Node->getValueType(0); 7172 unsigned VTBits = VT.getScalarSizeInBits(); 7173 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7174 7175 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7176 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7177 SDValue ShOpLo = Node->getOperand(0); 7178 SDValue ShOpHi = Node->getOperand(1); 7179 SDValue ShAmt = Node->getOperand(2); 7180 EVT ShAmtVT = ShAmt.getValueType(); 7181 EVT ShAmtCCVT = 7182 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7183 SDLoc dl(Node); 7184 7185 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7186 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7187 // away during isel. 7188 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7189 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7190 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7191 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7192 : DAG.getConstant(0, dl, VT); 7193 7194 SDValue Tmp2, Tmp3; 7195 if (IsSHL) { 7196 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7197 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7198 } else { 7199 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7200 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7201 } 7202 7203 // If the shift amount is larger or equal than the width of a part we don't 7204 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7205 // values for large shift amounts. 7206 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7207 DAG.getConstant(VTBits, dl, ShAmtVT)); 7208 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7209 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7210 7211 if (IsSHL) { 7212 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7213 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7214 } else { 7215 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7216 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7217 } 7218 } 7219 7220 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7221 SelectionDAG &DAG) const { 7222 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7223 SDValue Src = Node->getOperand(OpNo); 7224 EVT SrcVT = Src.getValueType(); 7225 EVT DstVT = Node->getValueType(0); 7226 SDLoc dl(SDValue(Node, 0)); 7227 7228 // FIXME: Only f32 to i64 conversions are supported. 7229 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7230 return false; 7231 7232 if (Node->isStrictFPOpcode()) 7233 // When a NaN is converted to an integer a trap is allowed. We can't 7234 // use this expansion here because it would eliminate that trap. Other 7235 // traps are also allowed and cannot be eliminated. See 7236 // IEEE 754-2008 sec 5.8. 7237 return false; 7238 7239 // Expand f32 -> i64 conversion 7240 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7241 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7242 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7243 EVT IntVT = SrcVT.changeTypeToInteger(); 7244 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7245 7246 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7247 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7248 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7249 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7250 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7251 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7252 7253 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7254 7255 SDValue ExponentBits = DAG.getNode( 7256 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7257 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7258 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7259 7260 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7261 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7262 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7263 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7264 7265 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7266 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7267 DAG.getConstant(0x00800000, dl, IntVT)); 7268 7269 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7270 7271 R = DAG.getSelectCC( 7272 dl, Exponent, ExponentLoBit, 7273 DAG.getNode(ISD::SHL, dl, DstVT, R, 7274 DAG.getZExtOrTrunc( 7275 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7276 dl, IntShVT)), 7277 DAG.getNode(ISD::SRL, dl, DstVT, R, 7278 DAG.getZExtOrTrunc( 7279 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7280 dl, IntShVT)), 7281 ISD::SETGT); 7282 7283 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7284 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7285 7286 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7287 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7288 return true; 7289 } 7290 7291 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7292 SDValue &Chain, 7293 SelectionDAG &DAG) const { 7294 SDLoc dl(SDValue(Node, 0)); 7295 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7296 SDValue Src = Node->getOperand(OpNo); 7297 7298 EVT SrcVT = Src.getValueType(); 7299 EVT DstVT = Node->getValueType(0); 7300 EVT SetCCVT = 7301 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7302 EVT DstSetCCVT = 7303 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7304 7305 // Only expand vector types if we have the appropriate vector bit operations. 7306 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7307 ISD::FP_TO_SINT; 7308 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7309 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7310 return false; 7311 7312 // If the maximum float value is smaller then the signed integer range, 7313 // the destination signmask can't be represented by the float, so we can 7314 // just use FP_TO_SINT directly. 7315 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7316 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7317 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7318 if (APFloat::opOverflow & 7319 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7320 if (Node->isStrictFPOpcode()) { 7321 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7322 { Node->getOperand(0), Src }); 7323 Chain = Result.getValue(1); 7324 } else 7325 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7326 return true; 7327 } 7328 7329 // Don't expand it if there isn't cheap fsub instruction. 7330 if (!isOperationLegalOrCustom( 7331 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7332 return false; 7333 7334 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7335 SDValue Sel; 7336 7337 if (Node->isStrictFPOpcode()) { 7338 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7339 Node->getOperand(0), /*IsSignaling*/ true); 7340 Chain = Sel.getValue(1); 7341 } else { 7342 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7343 } 7344 7345 bool Strict = Node->isStrictFPOpcode() || 7346 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7347 7348 if (Strict) { 7349 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7350 // signmask then offset (the result of which should be fully representable). 7351 // Sel = Src < 0x8000000000000000 7352 // FltOfs = select Sel, 0, 0x8000000000000000 7353 // IntOfs = select Sel, 0, 0x8000000000000000 7354 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7355 7356 // TODO: Should any fast-math-flags be set for the FSUB? 7357 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7358 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7359 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7360 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7361 DAG.getConstant(0, dl, DstVT), 7362 DAG.getConstant(SignMask, dl, DstVT)); 7363 SDValue SInt; 7364 if (Node->isStrictFPOpcode()) { 7365 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7366 { Chain, Src, FltOfs }); 7367 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7368 { Val.getValue(1), Val }); 7369 Chain = SInt.getValue(1); 7370 } else { 7371 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7372 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7373 } 7374 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7375 } else { 7376 // Expand based on maximum range of FP_TO_SINT: 7377 // True = fp_to_sint(Src) 7378 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7379 // Result = select (Src < 0x8000000000000000), True, False 7380 7381 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7382 // TODO: Should any fast-math-flags be set for the FSUB? 7383 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7384 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7385 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7386 DAG.getConstant(SignMask, dl, DstVT)); 7387 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7388 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7389 } 7390 return true; 7391 } 7392 7393 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7394 SDValue &Chain, 7395 SelectionDAG &DAG) const { 7396 // This transform is not correct for converting 0 when rounding mode is set 7397 // to round toward negative infinity which will produce -0.0. So disable under 7398 // strictfp. 7399 if (Node->isStrictFPOpcode()) 7400 return false; 7401 7402 SDValue Src = Node->getOperand(0); 7403 EVT SrcVT = Src.getValueType(); 7404 EVT DstVT = Node->getValueType(0); 7405 7406 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7407 return false; 7408 7409 // Only expand vector types if we have the appropriate vector bit operations. 7410 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7411 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7412 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7413 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7414 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7415 return false; 7416 7417 SDLoc dl(SDValue(Node, 0)); 7418 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7419 7420 // Implementation of unsigned i64 to f64 following the algorithm in 7421 // __floatundidf in compiler_rt. This implementation performs rounding 7422 // correctly in all rounding modes with the exception of converting 0 7423 // when rounding toward negative infinity. In that case the fsub will produce 7424 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7425 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7426 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7427 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7428 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7429 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7430 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7431 7432 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7433 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7434 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7435 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7436 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7437 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7438 SDValue HiSub = 7439 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7440 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7441 return true; 7442 } 7443 7444 SDValue 7445 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7446 SelectionDAG &DAG) const { 7447 unsigned Opcode = Node->getOpcode(); 7448 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7449 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7450 "Wrong opcode"); 7451 7452 if (Node->getFlags().hasNoNaNs()) { 7453 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7454 SDValue Op1 = Node->getOperand(0); 7455 SDValue Op2 = Node->getOperand(1); 7456 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7457 // Copy FMF flags, but always set the no-signed-zeros flag 7458 // as this is implied by the FMINNUM/FMAXNUM semantics. 7459 SDNodeFlags Flags = Node->getFlags(); 7460 Flags.setNoSignedZeros(true); 7461 SelCC->setFlags(Flags); 7462 return SelCC; 7463 } 7464 7465 return SDValue(); 7466 } 7467 7468 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7469 SelectionDAG &DAG) const { 7470 SDLoc dl(Node); 7471 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7472 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7473 EVT VT = Node->getValueType(0); 7474 7475 if (VT.isScalableVector()) 7476 report_fatal_error( 7477 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7478 7479 if (isOperationLegalOrCustom(NewOp, VT)) { 7480 SDValue Quiet0 = Node->getOperand(0); 7481 SDValue Quiet1 = Node->getOperand(1); 7482 7483 if (!Node->getFlags().hasNoNaNs()) { 7484 // Insert canonicalizes if it's possible we need to quiet to get correct 7485 // sNaN behavior. 7486 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7487 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7488 Node->getFlags()); 7489 } 7490 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7491 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7492 Node->getFlags()); 7493 } 7494 } 7495 7496 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7497 } 7498 7499 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7500 // instead if there are no NaNs. 7501 if (Node->getFlags().hasNoNaNs()) { 7502 unsigned IEEE2018Op = 7503 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7504 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7505 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7506 Node->getOperand(1), Node->getFlags()); 7507 } 7508 } 7509 7510 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7511 return SelCC; 7512 7513 return SDValue(); 7514 } 7515 7516 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7517 unsigned Test, SDNodeFlags Flags, 7518 const SDLoc &DL, 7519 SelectionDAG &DAG) const { 7520 EVT OperandVT = Op.getValueType(); 7521 assert(OperandVT.isFloatingPoint()); 7522 7523 // Degenerated cases. 7524 if (Test == 0) 7525 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7526 if ((Test & fcAllFlags) == fcAllFlags) 7527 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7528 7529 // PPC double double is a pair of doubles, of which the higher part determines 7530 // the value class. 7531 if (OperandVT == MVT::ppcf128) { 7532 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7533 DAG.getConstant(1, DL, MVT::i32)); 7534 OperandVT = MVT::f64; 7535 } 7536 7537 // Some checks may be represented as inversion of simpler check, for example 7538 // "inf|normal|subnormal|zero" => !"nan". 7539 bool IsInverted = false; 7540 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7541 IsInverted = true; 7542 Test = InvertedCheck; 7543 } 7544 7545 // Floating-point type properties. 7546 EVT ScalarFloatVT = OperandVT.getScalarType(); 7547 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7548 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7549 bool IsF80 = (ScalarFloatVT == MVT::f80); 7550 7551 // Some checks can be implemented using float comparisons, if floating point 7552 // exceptions are ignored. 7553 if (Flags.hasNoFPExcept() && 7554 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7555 if (Test == fcZero) 7556 return DAG.getSetCC(DL, ResultVT, Op, 7557 DAG.getConstantFP(0.0, DL, OperandVT), 7558 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7559 if (Test == fcNan) 7560 return DAG.getSetCC(DL, ResultVT, Op, Op, 7561 IsInverted ? ISD::SETO : ISD::SETUO); 7562 } 7563 7564 // In the general case use integer operations. 7565 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7566 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7567 if (OperandVT.isVector()) 7568 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7569 OperandVT.getVectorElementCount()); 7570 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7571 7572 // Various masks. 7573 APInt SignBit = APInt::getSignMask(BitSize); 7574 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7575 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7576 const unsigned ExplicitIntBitInF80 = 63; 7577 APInt ExpMask = Inf; 7578 if (IsF80) 7579 ExpMask.clearBit(ExplicitIntBitInF80); 7580 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7581 APInt QNaNBitMask = 7582 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7583 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7584 7585 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7586 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7587 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7588 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7589 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7590 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7591 7592 SDValue Res; 7593 const auto appendResult = [&](SDValue PartialRes) { 7594 if (PartialRes) { 7595 if (Res) 7596 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7597 else 7598 Res = PartialRes; 7599 } 7600 }; 7601 7602 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7603 const auto getIntBitIsSet = [&]() -> SDValue { 7604 if (!IntBitIsSetV) { 7605 APInt IntBitMask(BitSize, 0); 7606 IntBitMask.setBit(ExplicitIntBitInF80); 7607 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7608 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7609 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7610 } 7611 return IntBitIsSetV; 7612 }; 7613 7614 // Split the value into sign bit and absolute value. 7615 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7616 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7617 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7618 7619 // Tests that involve more than one class should be processed first. 7620 SDValue PartialRes; 7621 7622 if (IsF80) 7623 ; // Detect finite numbers of f80 by checking individual classes because 7624 // they have different settings of the explicit integer bit. 7625 else if ((Test & fcFinite) == fcFinite) { 7626 // finite(V) ==> abs(V) < exp_mask 7627 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7628 Test &= ~fcFinite; 7629 } else if ((Test & fcFinite) == fcPosFinite) { 7630 // finite(V) && V > 0 ==> V < exp_mask 7631 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7632 Test &= ~fcPosFinite; 7633 } else if ((Test & fcFinite) == fcNegFinite) { 7634 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7635 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7636 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7637 Test &= ~fcNegFinite; 7638 } 7639 appendResult(PartialRes); 7640 7641 // Check for individual classes. 7642 7643 if (unsigned PartialCheck = Test & fcZero) { 7644 if (PartialCheck == fcPosZero) 7645 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7646 else if (PartialCheck == fcZero) 7647 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7648 else // ISD::fcNegZero 7649 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7650 appendResult(PartialRes); 7651 } 7652 7653 if (unsigned PartialCheck = Test & fcInf) { 7654 if (PartialCheck == fcPosInf) 7655 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7656 else if (PartialCheck == fcInf) 7657 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7658 else { // ISD::fcNegInf 7659 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7660 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7661 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7662 } 7663 appendResult(PartialRes); 7664 } 7665 7666 if (unsigned PartialCheck = Test & fcNan) { 7667 APInt InfWithQnanBit = Inf | QNaNBitMask; 7668 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7669 if (PartialCheck == fcNan) { 7670 // isnan(V) ==> abs(V) > int(inf) 7671 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7672 if (IsF80) { 7673 // Recognize unsupported values as NaNs for compatibility with glibc. 7674 // In them (exp(V)==0) == int_bit. 7675 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7676 SDValue ExpIsZero = 7677 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7678 SDValue IsPseudo = 7679 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7680 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7681 } 7682 } else if (PartialCheck == fcQNan) { 7683 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7684 PartialRes = 7685 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7686 } else { // ISD::fcSNan 7687 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7688 // abs(V) < (unsigned(Inf) | quiet_bit) 7689 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7690 SDValue IsNotQnan = 7691 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7692 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7693 } 7694 appendResult(PartialRes); 7695 } 7696 7697 if (unsigned PartialCheck = Test & fcSubnormal) { 7698 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7699 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7700 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7701 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7702 SDValue VMinusOneV = 7703 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7704 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7705 if (PartialCheck == fcNegSubnormal) 7706 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7707 appendResult(PartialRes); 7708 } 7709 7710 if (unsigned PartialCheck = Test & fcNormal) { 7711 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7712 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7713 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7714 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7715 APInt ExpLimit = ExpMask - ExpLSB; 7716 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7717 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7718 if (PartialCheck == fcNegNormal) 7719 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7720 else if (PartialCheck == fcPosNormal) { 7721 SDValue PosSignV = 7722 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7723 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7724 } 7725 if (IsF80) 7726 PartialRes = 7727 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7728 appendResult(PartialRes); 7729 } 7730 7731 if (!Res) 7732 return DAG.getConstant(IsInverted, DL, ResultVT); 7733 if (IsInverted) 7734 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7735 return Res; 7736 } 7737 7738 // Only expand vector types if we have the appropriate vector bit operations. 7739 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7740 assert(VT.isVector() && "Expected vector type"); 7741 unsigned Len = VT.getScalarSizeInBits(); 7742 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7743 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7744 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7745 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7746 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7747 } 7748 7749 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7750 SDLoc dl(Node); 7751 EVT VT = Node->getValueType(0); 7752 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7753 SDValue Op = Node->getOperand(0); 7754 unsigned Len = VT.getScalarSizeInBits(); 7755 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7756 7757 // TODO: Add support for irregular type lengths. 7758 if (!(Len <= 128 && Len % 8 == 0)) 7759 return SDValue(); 7760 7761 // Only expand vector types if we have the appropriate vector bit operations. 7762 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7763 return SDValue(); 7764 7765 // This is the "best" algorithm from 7766 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7767 SDValue Mask55 = 7768 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7769 SDValue Mask33 = 7770 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7771 SDValue Mask0F = 7772 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7773 7774 // v = v - ((v >> 1) & 0x55555555...) 7775 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7776 DAG.getNode(ISD::AND, dl, VT, 7777 DAG.getNode(ISD::SRL, dl, VT, Op, 7778 DAG.getConstant(1, dl, ShVT)), 7779 Mask55)); 7780 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7781 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7782 DAG.getNode(ISD::AND, dl, VT, 7783 DAG.getNode(ISD::SRL, dl, VT, Op, 7784 DAG.getConstant(2, dl, ShVT)), 7785 Mask33)); 7786 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7787 Op = DAG.getNode(ISD::AND, dl, VT, 7788 DAG.getNode(ISD::ADD, dl, VT, Op, 7789 DAG.getNode(ISD::SRL, dl, VT, Op, 7790 DAG.getConstant(4, dl, ShVT))), 7791 Mask0F); 7792 7793 if (Len <= 8) 7794 return Op; 7795 7796 // Avoid the multiply if we only have 2 bytes to add. 7797 // TODO: Only doing this for scalars because vectors weren't as obviously 7798 // improved. 7799 if (Len == 16 && !VT.isVector()) { 7800 // v = (v + (v >> 8)) & 0x00FF; 7801 return DAG.getNode(ISD::AND, dl, VT, 7802 DAG.getNode(ISD::ADD, dl, VT, Op, 7803 DAG.getNode(ISD::SRL, dl, VT, Op, 7804 DAG.getConstant(8, dl, ShVT))), 7805 DAG.getConstant(0xFF, dl, VT)); 7806 } 7807 7808 // v = (v * 0x01010101...) >> (Len - 8) 7809 SDValue Mask01 = 7810 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7811 return DAG.getNode(ISD::SRL, dl, VT, 7812 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7813 DAG.getConstant(Len - 8, dl, ShVT)); 7814 } 7815 7816 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7817 SDLoc dl(Node); 7818 EVT VT = Node->getValueType(0); 7819 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7820 SDValue Op = Node->getOperand(0); 7821 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7822 7823 // If the non-ZERO_UNDEF version is supported we can use that instead. 7824 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7825 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7826 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7827 7828 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7829 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7830 EVT SetCCVT = 7831 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7832 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7833 SDValue Zero = DAG.getConstant(0, dl, VT); 7834 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7835 return DAG.getSelect(dl, VT, SrcIsZero, 7836 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7837 } 7838 7839 // Only expand vector types if we have the appropriate vector bit operations. 7840 // This includes the operations needed to expand CTPOP if it isn't supported. 7841 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7842 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7843 !canExpandVectorCTPOP(*this, VT)) || 7844 !isOperationLegalOrCustom(ISD::SRL, VT) || 7845 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7846 return SDValue(); 7847 7848 // for now, we do this: 7849 // x = x | (x >> 1); 7850 // x = x | (x >> 2); 7851 // ... 7852 // x = x | (x >>16); 7853 // x = x | (x >>32); // for 64-bit input 7854 // return popcount(~x); 7855 // 7856 // Ref: "Hacker's Delight" by Henry Warren 7857 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 7858 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7859 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7860 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7861 } 7862 Op = DAG.getNOT(dl, Op, VT); 7863 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7864 } 7865 7866 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7867 SDLoc dl(Node); 7868 EVT VT = Node->getValueType(0); 7869 SDValue Op = Node->getOperand(0); 7870 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7871 7872 // If the non-ZERO_UNDEF version is supported we can use that instead. 7873 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7874 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7875 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7876 7877 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7878 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7879 EVT SetCCVT = 7880 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7881 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7882 SDValue Zero = DAG.getConstant(0, dl, VT); 7883 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7884 return DAG.getSelect(dl, VT, SrcIsZero, 7885 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7886 } 7887 7888 // Only expand vector types if we have the appropriate vector bit operations. 7889 // This includes the operations needed to expand CTPOP if it isn't supported. 7890 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7891 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7892 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7893 !canExpandVectorCTPOP(*this, VT)) || 7894 !isOperationLegalOrCustom(ISD::SUB, VT) || 7895 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7896 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7897 return SDValue(); 7898 7899 // for now, we use: { return popcount(~x & (x - 1)); } 7900 // unless the target has ctlz but not ctpop, in which case we use: 7901 // { return 32 - nlz(~x & (x-1)); } 7902 // Ref: "Hacker's Delight" by Henry Warren 7903 SDValue Tmp = DAG.getNode( 7904 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7905 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7906 7907 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7908 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7909 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7910 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7911 } 7912 7913 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7914 } 7915 7916 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7917 bool IsNegative) const { 7918 SDLoc dl(N); 7919 EVT VT = N->getValueType(0); 7920 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7921 SDValue Op = N->getOperand(0); 7922 7923 // abs(x) -> smax(x,sub(0,x)) 7924 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7925 isOperationLegal(ISD::SMAX, VT)) { 7926 SDValue Zero = DAG.getConstant(0, dl, VT); 7927 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7928 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7929 } 7930 7931 // abs(x) -> umin(x,sub(0,x)) 7932 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7933 isOperationLegal(ISD::UMIN, VT)) { 7934 SDValue Zero = DAG.getConstant(0, dl, VT); 7935 Op = DAG.getFreeze(Op); 7936 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7937 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7938 } 7939 7940 // 0 - abs(x) -> smin(x, sub(0,x)) 7941 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7942 isOperationLegal(ISD::SMIN, VT)) { 7943 Op = DAG.getFreeze(Op); 7944 SDValue Zero = DAG.getConstant(0, dl, VT); 7945 return DAG.getNode(ISD::SMIN, dl, VT, Op, 7946 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7947 } 7948 7949 // Only expand vector types if we have the appropriate vector operations. 7950 if (VT.isVector() && 7951 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7952 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7953 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7954 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7955 return SDValue(); 7956 7957 Op = DAG.getFreeze(Op); 7958 SDValue Shift = 7959 DAG.getNode(ISD::SRA, dl, VT, Op, 7960 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7961 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7962 7963 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 7964 if (!IsNegative) 7965 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 7966 7967 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7968 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7969 } 7970 7971 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7972 SDLoc dl(N); 7973 EVT VT = N->getValueType(0); 7974 SDValue Op = N->getOperand(0); 7975 7976 if (!VT.isSimple()) 7977 return SDValue(); 7978 7979 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7980 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7981 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7982 default: 7983 return SDValue(); 7984 case MVT::i16: 7985 // Use a rotate by 8. This can be further expanded if necessary. 7986 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7987 case MVT::i32: 7988 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7989 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7990 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7991 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7992 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7993 DAG.getConstant(0xFF0000, dl, VT)); 7994 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7995 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7996 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7997 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7998 case MVT::i64: 7999 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8000 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8001 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8002 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8003 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8004 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8005 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8006 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8007 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 8008 DAG.getConstant(255ULL<<48, dl, VT)); 8009 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 8010 DAG.getConstant(255ULL<<40, dl, VT)); 8011 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 8012 DAG.getConstant(255ULL<<32, dl, VT)); 8013 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 8014 DAG.getConstant(255ULL<<24, dl, VT)); 8015 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8016 DAG.getConstant(255ULL<<16, dl, VT)); 8017 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 8018 DAG.getConstant(255ULL<<8 , dl, VT)); 8019 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 8020 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 8021 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8022 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8023 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 8024 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8025 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 8026 } 8027 } 8028 8029 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 8030 SDLoc dl(N); 8031 EVT VT = N->getValueType(0); 8032 SDValue Op = N->getOperand(0); 8033 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8034 unsigned Sz = VT.getScalarSizeInBits(); 8035 8036 SDValue Tmp, Tmp2, Tmp3; 8037 8038 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 8039 // and finally the i1 pairs. 8040 // TODO: We can easily support i4/i2 legal types if any target ever does. 8041 if (Sz >= 8 && isPowerOf2_32(Sz)) { 8042 // Create the masks - repeating the pattern every byte. 8043 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 8044 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 8045 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 8046 8047 // BSWAP if the type is wider than a single byte. 8048 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 8049 8050 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 8051 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 8052 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 8053 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 8054 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8055 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8056 8057 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8058 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8059 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8060 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8061 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8062 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8063 8064 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8065 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8066 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8067 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8068 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8069 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8070 return Tmp; 8071 } 8072 8073 Tmp = DAG.getConstant(0, dl, VT); 8074 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8075 if (I < J) 8076 Tmp2 = 8077 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8078 else 8079 Tmp2 = 8080 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8081 8082 APInt Shift(Sz, 1); 8083 Shift <<= J; 8084 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8085 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8086 } 8087 8088 return Tmp; 8089 } 8090 8091 std::pair<SDValue, SDValue> 8092 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8093 SelectionDAG &DAG) const { 8094 SDLoc SL(LD); 8095 SDValue Chain = LD->getChain(); 8096 SDValue BasePTR = LD->getBasePtr(); 8097 EVT SrcVT = LD->getMemoryVT(); 8098 EVT DstVT = LD->getValueType(0); 8099 ISD::LoadExtType ExtType = LD->getExtensionType(); 8100 8101 if (SrcVT.isScalableVector()) 8102 report_fatal_error("Cannot scalarize scalable vector loads"); 8103 8104 unsigned NumElem = SrcVT.getVectorNumElements(); 8105 8106 EVT SrcEltVT = SrcVT.getScalarType(); 8107 EVT DstEltVT = DstVT.getScalarType(); 8108 8109 // A vector must always be stored in memory as-is, i.e. without any padding 8110 // between the elements, since various code depend on it, e.g. in the 8111 // handling of a bitcast of a vector type to int, which may be done with a 8112 // vector store followed by an integer load. A vector that does not have 8113 // elements that are byte-sized must therefore be stored as an integer 8114 // built out of the extracted vector elements. 8115 if (!SrcEltVT.isByteSized()) { 8116 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8117 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8118 8119 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8120 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8121 8122 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8123 SDValue SrcEltBitMask = DAG.getConstant( 8124 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8125 8126 // Load the whole vector and avoid masking off the top bits as it makes 8127 // the codegen worse. 8128 SDValue Load = 8129 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8130 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8131 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8132 8133 SmallVector<SDValue, 8> Vals; 8134 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8135 unsigned ShiftIntoIdx = 8136 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8137 SDValue ShiftAmount = 8138 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8139 LoadVT, SL, /*LegalTypes=*/false); 8140 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8141 SDValue Elt = 8142 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8143 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8144 8145 if (ExtType != ISD::NON_EXTLOAD) { 8146 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8147 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8148 } 8149 8150 Vals.push_back(Scalar); 8151 } 8152 8153 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8154 return std::make_pair(Value, Load.getValue(1)); 8155 } 8156 8157 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8158 assert(SrcEltVT.isByteSized()); 8159 8160 SmallVector<SDValue, 8> Vals; 8161 SmallVector<SDValue, 8> LoadChains; 8162 8163 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8164 SDValue ScalarLoad = 8165 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8166 LD->getPointerInfo().getWithOffset(Idx * Stride), 8167 SrcEltVT, LD->getOriginalAlign(), 8168 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8169 8170 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8171 8172 Vals.push_back(ScalarLoad.getValue(0)); 8173 LoadChains.push_back(ScalarLoad.getValue(1)); 8174 } 8175 8176 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8177 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8178 8179 return std::make_pair(Value, NewChain); 8180 } 8181 8182 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8183 SelectionDAG &DAG) const { 8184 SDLoc SL(ST); 8185 8186 SDValue Chain = ST->getChain(); 8187 SDValue BasePtr = ST->getBasePtr(); 8188 SDValue Value = ST->getValue(); 8189 EVT StVT = ST->getMemoryVT(); 8190 8191 if (StVT.isScalableVector()) 8192 report_fatal_error("Cannot scalarize scalable vector stores"); 8193 8194 // The type of the data we want to save 8195 EVT RegVT = Value.getValueType(); 8196 EVT RegSclVT = RegVT.getScalarType(); 8197 8198 // The type of data as saved in memory. 8199 EVT MemSclVT = StVT.getScalarType(); 8200 8201 unsigned NumElem = StVT.getVectorNumElements(); 8202 8203 // A vector must always be stored in memory as-is, i.e. without any padding 8204 // between the elements, since various code depend on it, e.g. in the 8205 // handling of a bitcast of a vector type to int, which may be done with a 8206 // vector store followed by an integer load. A vector that does not have 8207 // elements that are byte-sized must therefore be stored as an integer 8208 // built out of the extracted vector elements. 8209 if (!MemSclVT.isByteSized()) { 8210 unsigned NumBits = StVT.getSizeInBits(); 8211 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8212 8213 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8214 8215 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8216 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8217 DAG.getVectorIdxConstant(Idx, SL)); 8218 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8219 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8220 unsigned ShiftIntoIdx = 8221 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8222 SDValue ShiftAmount = 8223 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8224 SDValue ShiftedElt = 8225 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8226 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8227 } 8228 8229 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8230 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8231 ST->getAAInfo()); 8232 } 8233 8234 // Store Stride in bytes 8235 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8236 assert(Stride && "Zero stride!"); 8237 // Extract each of the elements from the original vector and save them into 8238 // memory individually. 8239 SmallVector<SDValue, 8> Stores; 8240 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8241 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8242 DAG.getVectorIdxConstant(Idx, SL)); 8243 8244 SDValue Ptr = 8245 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8246 8247 // This scalar TruncStore may be illegal, but we legalize it later. 8248 SDValue Store = DAG.getTruncStore( 8249 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8250 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8251 ST->getAAInfo()); 8252 8253 Stores.push_back(Store); 8254 } 8255 8256 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8257 } 8258 8259 std::pair<SDValue, SDValue> 8260 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8261 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8262 "unaligned indexed loads not implemented!"); 8263 SDValue Chain = LD->getChain(); 8264 SDValue Ptr = LD->getBasePtr(); 8265 EVT VT = LD->getValueType(0); 8266 EVT LoadedVT = LD->getMemoryVT(); 8267 SDLoc dl(LD); 8268 auto &MF = DAG.getMachineFunction(); 8269 8270 if (VT.isFloatingPoint() || VT.isVector()) { 8271 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8272 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8273 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8274 LoadedVT.isVector()) { 8275 // Scalarize the load and let the individual components be handled. 8276 return scalarizeVectorLoad(LD, DAG); 8277 } 8278 8279 // Expand to a (misaligned) integer load of the same size, 8280 // then bitconvert to floating point or vector. 8281 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8282 LD->getMemOperand()); 8283 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8284 if (LoadedVT != VT) 8285 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8286 ISD::ANY_EXTEND, dl, VT, Result); 8287 8288 return std::make_pair(Result, newLoad.getValue(1)); 8289 } 8290 8291 // Copy the value to a (aligned) stack slot using (unaligned) integer 8292 // loads and stores, then do a (aligned) load from the stack slot. 8293 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8294 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8295 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8296 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8297 8298 // Make sure the stack slot is also aligned for the register type. 8299 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8300 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8301 SmallVector<SDValue, 8> Stores; 8302 SDValue StackPtr = StackBase; 8303 unsigned Offset = 0; 8304 8305 EVT PtrVT = Ptr.getValueType(); 8306 EVT StackPtrVT = StackPtr.getValueType(); 8307 8308 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8309 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8310 8311 // Do all but one copies using the full register width. 8312 for (unsigned i = 1; i < NumRegs; i++) { 8313 // Load one integer register's worth from the original location. 8314 SDValue Load = DAG.getLoad( 8315 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8316 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8317 LD->getAAInfo()); 8318 // Follow the load with a store to the stack slot. Remember the store. 8319 Stores.push_back(DAG.getStore( 8320 Load.getValue(1), dl, Load, StackPtr, 8321 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8322 // Increment the pointers. 8323 Offset += RegBytes; 8324 8325 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8326 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8327 } 8328 8329 // The last copy may be partial. Do an extending load. 8330 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8331 8 * (LoadedBytes - Offset)); 8332 SDValue Load = 8333 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8334 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8335 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8336 LD->getAAInfo()); 8337 // Follow the load with a store to the stack slot. Remember the store. 8338 // On big-endian machines this requires a truncating store to ensure 8339 // that the bits end up in the right place. 8340 Stores.push_back(DAG.getTruncStore( 8341 Load.getValue(1), dl, Load, StackPtr, 8342 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8343 8344 // The order of the stores doesn't matter - say it with a TokenFactor. 8345 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8346 8347 // Finally, perform the original load only redirected to the stack slot. 8348 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8349 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8350 LoadedVT); 8351 8352 // Callers expect a MERGE_VALUES node. 8353 return std::make_pair(Load, TF); 8354 } 8355 8356 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8357 "Unaligned load of unsupported type."); 8358 8359 // Compute the new VT that is half the size of the old one. This is an 8360 // integer MVT. 8361 unsigned NumBits = LoadedVT.getSizeInBits(); 8362 EVT NewLoadedVT; 8363 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8364 NumBits >>= 1; 8365 8366 Align Alignment = LD->getOriginalAlign(); 8367 unsigned IncrementSize = NumBits / 8; 8368 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8369 8370 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8371 if (HiExtType == ISD::NON_EXTLOAD) 8372 HiExtType = ISD::ZEXTLOAD; 8373 8374 // Load the value in two parts 8375 SDValue Lo, Hi; 8376 if (DAG.getDataLayout().isLittleEndian()) { 8377 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8378 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8379 LD->getAAInfo()); 8380 8381 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8382 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8383 LD->getPointerInfo().getWithOffset(IncrementSize), 8384 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8385 LD->getAAInfo()); 8386 } else { 8387 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8388 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8389 LD->getAAInfo()); 8390 8391 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8392 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8393 LD->getPointerInfo().getWithOffset(IncrementSize), 8394 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8395 LD->getAAInfo()); 8396 } 8397 8398 // aggregate the two parts 8399 SDValue ShiftAmount = 8400 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8401 DAG.getDataLayout())); 8402 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8403 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8404 8405 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8406 Hi.getValue(1)); 8407 8408 return std::make_pair(Result, TF); 8409 } 8410 8411 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8412 SelectionDAG &DAG) const { 8413 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8414 "unaligned indexed stores not implemented!"); 8415 SDValue Chain = ST->getChain(); 8416 SDValue Ptr = ST->getBasePtr(); 8417 SDValue Val = ST->getValue(); 8418 EVT VT = Val.getValueType(); 8419 Align Alignment = ST->getOriginalAlign(); 8420 auto &MF = DAG.getMachineFunction(); 8421 EVT StoreMemVT = ST->getMemoryVT(); 8422 8423 SDLoc dl(ST); 8424 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8425 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8426 if (isTypeLegal(intVT)) { 8427 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8428 StoreMemVT.isVector()) { 8429 // Scalarize the store and let the individual components be handled. 8430 SDValue Result = scalarizeVectorStore(ST, DAG); 8431 return Result; 8432 } 8433 // Expand to a bitconvert of the value to the integer type of the 8434 // same size, then a (misaligned) int store. 8435 // FIXME: Does not handle truncating floating point stores! 8436 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8437 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8438 Alignment, ST->getMemOperand()->getFlags()); 8439 return Result; 8440 } 8441 // Do a (aligned) store to a stack slot, then copy from the stack slot 8442 // to the final destination using (unaligned) integer loads and stores. 8443 MVT RegVT = getRegisterType( 8444 *DAG.getContext(), 8445 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8446 EVT PtrVT = Ptr.getValueType(); 8447 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8448 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8449 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8450 8451 // Make sure the stack slot is also aligned for the register type. 8452 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8453 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8454 8455 // Perform the original store, only redirected to the stack slot. 8456 SDValue Store = DAG.getTruncStore( 8457 Chain, dl, Val, StackPtr, 8458 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8459 8460 EVT StackPtrVT = StackPtr.getValueType(); 8461 8462 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8463 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8464 SmallVector<SDValue, 8> Stores; 8465 unsigned Offset = 0; 8466 8467 // Do all but one copies using the full register width. 8468 for (unsigned i = 1; i < NumRegs; i++) { 8469 // Load one integer register's worth from the stack slot. 8470 SDValue Load = DAG.getLoad( 8471 RegVT, dl, Store, StackPtr, 8472 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8473 // Store it to the final location. Remember the store. 8474 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8475 ST->getPointerInfo().getWithOffset(Offset), 8476 ST->getOriginalAlign(), 8477 ST->getMemOperand()->getFlags())); 8478 // Increment the pointers. 8479 Offset += RegBytes; 8480 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8481 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8482 } 8483 8484 // The last store may be partial. Do a truncating store. On big-endian 8485 // machines this requires an extending load from the stack slot to ensure 8486 // that the bits are in the right place. 8487 EVT LoadMemVT = 8488 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8489 8490 // Load from the stack slot. 8491 SDValue Load = DAG.getExtLoad( 8492 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8493 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8494 8495 Stores.push_back( 8496 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8497 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8498 ST->getOriginalAlign(), 8499 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8500 // The order of the stores doesn't matter - say it with a TokenFactor. 8501 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8502 return Result; 8503 } 8504 8505 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8506 "Unaligned store of unknown type."); 8507 // Get the half-size VT 8508 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8509 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8510 unsigned IncrementSize = NumBits / 8; 8511 8512 // Divide the stored value in two parts. 8513 SDValue ShiftAmount = DAG.getConstant( 8514 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8515 SDValue Lo = Val; 8516 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8517 8518 // Store the two parts 8519 SDValue Store1, Store2; 8520 Store1 = DAG.getTruncStore(Chain, dl, 8521 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8522 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8523 ST->getMemOperand()->getFlags()); 8524 8525 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8526 Store2 = DAG.getTruncStore( 8527 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8528 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8529 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8530 8531 SDValue Result = 8532 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8533 return Result; 8534 } 8535 8536 SDValue 8537 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8538 const SDLoc &DL, EVT DataVT, 8539 SelectionDAG &DAG, 8540 bool IsCompressedMemory) const { 8541 SDValue Increment; 8542 EVT AddrVT = Addr.getValueType(); 8543 EVT MaskVT = Mask.getValueType(); 8544 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8545 "Incompatible types of Data and Mask"); 8546 if (IsCompressedMemory) { 8547 if (DataVT.isScalableVector()) 8548 report_fatal_error( 8549 "Cannot currently handle compressed memory with scalable vectors"); 8550 // Incrementing the pointer according to number of '1's in the mask. 8551 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8552 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8553 if (MaskIntVT.getSizeInBits() < 32) { 8554 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8555 MaskIntVT = MVT::i32; 8556 } 8557 8558 // Count '1's with POPCNT. 8559 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8560 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8561 // Scale is an element size in bytes. 8562 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8563 AddrVT); 8564 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8565 } else if (DataVT.isScalableVector()) { 8566 Increment = DAG.getVScale(DL, AddrVT, 8567 APInt(AddrVT.getFixedSizeInBits(), 8568 DataVT.getStoreSize().getKnownMinSize())); 8569 } else 8570 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8571 8572 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8573 } 8574 8575 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8576 EVT VecVT, const SDLoc &dl, 8577 ElementCount SubEC) { 8578 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8579 "Cannot index a scalable vector within a fixed-width vector"); 8580 8581 unsigned NElts = VecVT.getVectorMinNumElements(); 8582 unsigned NumSubElts = SubEC.getKnownMinValue(); 8583 EVT IdxVT = Idx.getValueType(); 8584 8585 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8586 // If this is a constant index and we know the value plus the number of the 8587 // elements in the subvector minus one is less than the minimum number of 8588 // elements then it's safe to return Idx. 8589 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8590 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8591 return Idx; 8592 SDValue VS = 8593 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8594 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8595 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8596 DAG.getConstant(NumSubElts, dl, IdxVT)); 8597 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8598 } 8599 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8600 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8601 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8602 DAG.getConstant(Imm, dl, IdxVT)); 8603 } 8604 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8605 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8606 DAG.getConstant(MaxIndex, dl, IdxVT)); 8607 } 8608 8609 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8610 SDValue VecPtr, EVT VecVT, 8611 SDValue Index) const { 8612 return getVectorSubVecPointer( 8613 DAG, VecPtr, VecVT, 8614 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8615 Index); 8616 } 8617 8618 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8619 SDValue VecPtr, EVT VecVT, 8620 EVT SubVecVT, 8621 SDValue Index) const { 8622 SDLoc dl(Index); 8623 // Make sure the index type is big enough to compute in. 8624 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8625 8626 EVT EltVT = VecVT.getVectorElementType(); 8627 8628 // Calculate the element offset and add it to the pointer. 8629 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8630 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8631 "Converting bits to bytes lost precision"); 8632 assert(SubVecVT.getVectorElementType() == EltVT && 8633 "Sub-vector must be a vector with matching element type"); 8634 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8635 SubVecVT.getVectorElementCount()); 8636 8637 EVT IdxVT = Index.getValueType(); 8638 if (SubVecVT.isScalableVector()) 8639 Index = 8640 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8641 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8642 8643 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8644 DAG.getConstant(EltSize, dl, IdxVT)); 8645 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8646 } 8647 8648 //===----------------------------------------------------------------------===// 8649 // Implementation of Emulated TLS Model 8650 //===----------------------------------------------------------------------===// 8651 8652 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8653 SelectionDAG &DAG) const { 8654 // Access to address of TLS varialbe xyz is lowered to a function call: 8655 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8656 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8657 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8658 SDLoc dl(GA); 8659 8660 ArgListTy Args; 8661 ArgListEntry Entry; 8662 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8663 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8664 StringRef EmuTlsVarName(NameString); 8665 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8666 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8667 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8668 Entry.Ty = VoidPtrType; 8669 Args.push_back(Entry); 8670 8671 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8672 8673 TargetLowering::CallLoweringInfo CLI(DAG); 8674 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8675 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8676 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8677 8678 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8679 // At last for X86 targets, maybe good for other targets too? 8680 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8681 MFI.setAdjustsStack(true); // Is this only for X86 target? 8682 MFI.setHasCalls(true); 8683 8684 assert((GA->getOffset() == 0) && 8685 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8686 return CallResult.first; 8687 } 8688 8689 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8690 SelectionDAG &DAG) const { 8691 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8692 if (!isCtlzFast()) 8693 return SDValue(); 8694 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8695 SDLoc dl(Op); 8696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8697 if (C->isZero() && CC == ISD::SETEQ) { 8698 EVT VT = Op.getOperand(0).getValueType(); 8699 SDValue Zext = Op.getOperand(0); 8700 if (VT.bitsLT(MVT::i32)) { 8701 VT = MVT::i32; 8702 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8703 } 8704 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8705 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8706 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8707 DAG.getConstant(Log2b, dl, MVT::i32)); 8708 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8709 } 8710 } 8711 return SDValue(); 8712 } 8713 8714 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8715 SDValue Op0 = Node->getOperand(0); 8716 SDValue Op1 = Node->getOperand(1); 8717 EVT VT = Op0.getValueType(); 8718 unsigned Opcode = Node->getOpcode(); 8719 SDLoc DL(Node); 8720 8721 // umin(x,y) -> sub(x,usubsat(x,y)) 8722 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8723 isOperationLegal(ISD::USUBSAT, VT)) { 8724 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8725 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8726 } 8727 8728 // umax(x,y) -> add(x,usubsat(y,x)) 8729 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8730 isOperationLegal(ISD::USUBSAT, VT)) { 8731 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8732 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8733 } 8734 8735 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8736 ISD::CondCode CC; 8737 switch (Opcode) { 8738 default: llvm_unreachable("How did we get here?"); 8739 case ISD::SMAX: CC = ISD::SETGT; break; 8740 case ISD::SMIN: CC = ISD::SETLT; break; 8741 case ISD::UMAX: CC = ISD::SETUGT; break; 8742 case ISD::UMIN: CC = ISD::SETULT; break; 8743 } 8744 8745 // FIXME: Should really try to split the vector in case it's legal on a 8746 // subvector. 8747 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8748 return DAG.UnrollVectorOp(Node); 8749 8750 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8751 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8752 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8753 } 8754 8755 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8756 unsigned Opcode = Node->getOpcode(); 8757 SDValue LHS = Node->getOperand(0); 8758 SDValue RHS = Node->getOperand(1); 8759 EVT VT = LHS.getValueType(); 8760 SDLoc dl(Node); 8761 8762 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8763 assert(VT.isInteger() && "Expected operands to be integers"); 8764 8765 // usub.sat(a, b) -> umax(a, b) - b 8766 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8767 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8768 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8769 } 8770 8771 // uadd.sat(a, b) -> umin(a, ~b) + b 8772 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8773 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8774 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8775 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8776 } 8777 8778 unsigned OverflowOp; 8779 switch (Opcode) { 8780 case ISD::SADDSAT: 8781 OverflowOp = ISD::SADDO; 8782 break; 8783 case ISD::UADDSAT: 8784 OverflowOp = ISD::UADDO; 8785 break; 8786 case ISD::SSUBSAT: 8787 OverflowOp = ISD::SSUBO; 8788 break; 8789 case ISD::USUBSAT: 8790 OverflowOp = ISD::USUBO; 8791 break; 8792 default: 8793 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8794 "addition or subtraction node."); 8795 } 8796 8797 // FIXME: Should really try to split the vector in case it's legal on a 8798 // subvector. 8799 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8800 return DAG.UnrollVectorOp(Node); 8801 8802 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8803 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8804 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8805 SDValue SumDiff = Result.getValue(0); 8806 SDValue Overflow = Result.getValue(1); 8807 SDValue Zero = DAG.getConstant(0, dl, VT); 8808 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8809 8810 if (Opcode == ISD::UADDSAT) { 8811 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8812 // (LHS + RHS) | OverflowMask 8813 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8814 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8815 } 8816 // Overflow ? 0xffff.... : (LHS + RHS) 8817 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8818 } 8819 8820 if (Opcode == ISD::USUBSAT) { 8821 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8822 // (LHS - RHS) & ~OverflowMask 8823 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8824 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8825 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8826 } 8827 // Overflow ? 0 : (LHS - RHS) 8828 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8829 } 8830 8831 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8832 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8833 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8834 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8835 DAG.getConstant(BitWidth - 1, dl, VT)); 8836 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8837 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8838 } 8839 8840 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8841 unsigned Opcode = Node->getOpcode(); 8842 bool IsSigned = Opcode == ISD::SSHLSAT; 8843 SDValue LHS = Node->getOperand(0); 8844 SDValue RHS = Node->getOperand(1); 8845 EVT VT = LHS.getValueType(); 8846 SDLoc dl(Node); 8847 8848 assert((Node->getOpcode() == ISD::SSHLSAT || 8849 Node->getOpcode() == ISD::USHLSAT) && 8850 "Expected a SHLSAT opcode"); 8851 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8852 assert(VT.isInteger() && "Expected operands to be integers"); 8853 8854 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8855 8856 unsigned BW = VT.getScalarSizeInBits(); 8857 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8858 SDValue Orig = 8859 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8860 8861 SDValue SatVal; 8862 if (IsSigned) { 8863 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8864 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8865 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8866 SatMin, SatMax, ISD::SETLT); 8867 } else { 8868 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8869 } 8870 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8871 8872 return Result; 8873 } 8874 8875 SDValue 8876 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8877 assert((Node->getOpcode() == ISD::SMULFIX || 8878 Node->getOpcode() == ISD::UMULFIX || 8879 Node->getOpcode() == ISD::SMULFIXSAT || 8880 Node->getOpcode() == ISD::UMULFIXSAT) && 8881 "Expected a fixed point multiplication opcode"); 8882 8883 SDLoc dl(Node); 8884 SDValue LHS = Node->getOperand(0); 8885 SDValue RHS = Node->getOperand(1); 8886 EVT VT = LHS.getValueType(); 8887 unsigned Scale = Node->getConstantOperandVal(2); 8888 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8889 Node->getOpcode() == ISD::UMULFIXSAT); 8890 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8891 Node->getOpcode() == ISD::SMULFIXSAT); 8892 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8893 unsigned VTSize = VT.getScalarSizeInBits(); 8894 8895 if (!Scale) { 8896 // [us]mul.fix(a, b, 0) -> mul(a, b) 8897 if (!Saturating) { 8898 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8899 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8900 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8901 SDValue Result = 8902 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8903 SDValue Product = Result.getValue(0); 8904 SDValue Overflow = Result.getValue(1); 8905 SDValue Zero = DAG.getConstant(0, dl, VT); 8906 8907 APInt MinVal = APInt::getSignedMinValue(VTSize); 8908 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8909 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8910 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8911 // Xor the inputs, if resulting sign bit is 0 the product will be 8912 // positive, else negative. 8913 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8914 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8915 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8916 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8917 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8918 SDValue Result = 8919 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8920 SDValue Product = Result.getValue(0); 8921 SDValue Overflow = Result.getValue(1); 8922 8923 APInt MaxVal = APInt::getMaxValue(VTSize); 8924 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8925 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8926 } 8927 } 8928 8929 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8930 "Expected scale to be less than the number of bits if signed or at " 8931 "most the number of bits if unsigned."); 8932 assert(LHS.getValueType() == RHS.getValueType() && 8933 "Expected both operands to be the same type"); 8934 8935 // Get the upper and lower bits of the result. 8936 SDValue Lo, Hi; 8937 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8938 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8939 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8940 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8941 Lo = Result.getValue(0); 8942 Hi = Result.getValue(1); 8943 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8944 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8945 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8946 } else if (VT.isVector()) { 8947 return SDValue(); 8948 } else { 8949 report_fatal_error("Unable to expand fixed point multiplication."); 8950 } 8951 8952 if (Scale == VTSize) 8953 // Result is just the top half since we'd be shifting by the width of the 8954 // operand. Overflow impossible so this works for both UMULFIX and 8955 // UMULFIXSAT. 8956 return Hi; 8957 8958 // The result will need to be shifted right by the scale since both operands 8959 // are scaled. The result is given to us in 2 halves, so we only want part of 8960 // both in the result. 8961 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8962 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8963 DAG.getConstant(Scale, dl, ShiftTy)); 8964 if (!Saturating) 8965 return Result; 8966 8967 if (!Signed) { 8968 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8969 // widened multiplication) aren't all zeroes. 8970 8971 // Saturate to max if ((Hi >> Scale) != 0), 8972 // which is the same as if (Hi > ((1 << Scale) - 1)) 8973 APInt MaxVal = APInt::getMaxValue(VTSize); 8974 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8975 dl, VT); 8976 Result = DAG.getSelectCC(dl, Hi, LowMask, 8977 DAG.getConstant(MaxVal, dl, VT), Result, 8978 ISD::SETUGT); 8979 8980 return Result; 8981 } 8982 8983 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8984 // widened multiplication) aren't all ones or all zeroes. 8985 8986 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8987 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8988 8989 if (Scale == 0) { 8990 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8991 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8992 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8993 // Saturated to SatMin if wide product is negative, and SatMax if wide 8994 // product is positive ... 8995 SDValue Zero = DAG.getConstant(0, dl, VT); 8996 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8997 ISD::SETLT); 8998 // ... but only if we overflowed. 8999 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 9000 } 9001 9002 // We handled Scale==0 above so all the bits to examine is in Hi. 9003 9004 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 9005 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 9006 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 9007 dl, VT); 9008 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 9009 // Saturate to min if (Hi >> (Scale - 1)) < -1), 9010 // which is the same as if (HI < (-1 << (Scale - 1)) 9011 SDValue HighMask = 9012 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 9013 dl, VT); 9014 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 9015 return Result; 9016 } 9017 9018 SDValue 9019 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 9020 SDValue LHS, SDValue RHS, 9021 unsigned Scale, SelectionDAG &DAG) const { 9022 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 9023 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 9024 "Expected a fixed point division opcode"); 9025 9026 EVT VT = LHS.getValueType(); 9027 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 9028 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 9029 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9030 9031 // If there is enough room in the type to upscale the LHS or downscale the 9032 // RHS before the division, we can perform it in this type without having to 9033 // resize. For signed operations, the LHS headroom is the number of 9034 // redundant sign bits, and for unsigned ones it is the number of zeroes. 9035 // The headroom for the RHS is the number of trailing zeroes. 9036 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 9037 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 9038 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 9039 9040 // For signed saturating operations, we need to be able to detect true integer 9041 // division overflow; that is, when you have MIN / -EPS. However, this 9042 // is undefined behavior and if we emit divisions that could take such 9043 // values it may cause undesired behavior (arithmetic exceptions on x86, for 9044 // example). 9045 // Avoid this by requiring an extra bit so that we never get this case. 9046 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 9047 // signed saturating division, we need to emit a whopping 32-bit division. 9048 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 9049 return SDValue(); 9050 9051 unsigned LHSShift = std::min(LHSLead, Scale); 9052 unsigned RHSShift = Scale - LHSShift; 9053 9054 // At this point, we know that if we shift the LHS up by LHSShift and the 9055 // RHS down by RHSShift, we can emit a regular division with a final scaling 9056 // factor of Scale. 9057 9058 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9059 if (LHSShift) 9060 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9061 DAG.getConstant(LHSShift, dl, ShiftTy)); 9062 if (RHSShift) 9063 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9064 DAG.getConstant(RHSShift, dl, ShiftTy)); 9065 9066 SDValue Quot; 9067 if (Signed) { 9068 // For signed operations, if the resulting quotient is negative and the 9069 // remainder is nonzero, subtract 1 from the quotient to round towards 9070 // negative infinity. 9071 SDValue Rem; 9072 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9073 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9074 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9075 if (isTypeLegal(VT) && 9076 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9077 Quot = DAG.getNode(ISD::SDIVREM, dl, 9078 DAG.getVTList(VT, VT), 9079 LHS, RHS); 9080 Rem = Quot.getValue(1); 9081 Quot = Quot.getValue(0); 9082 } else { 9083 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9084 LHS, RHS); 9085 Rem = DAG.getNode(ISD::SREM, dl, VT, 9086 LHS, RHS); 9087 } 9088 SDValue Zero = DAG.getConstant(0, dl, VT); 9089 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9090 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9091 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9092 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9093 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9094 DAG.getConstant(1, dl, VT)); 9095 Quot = DAG.getSelect(dl, VT, 9096 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9097 Sub1, Quot); 9098 } else 9099 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9100 LHS, RHS); 9101 9102 return Quot; 9103 } 9104 9105 void TargetLowering::expandUADDSUBO( 9106 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9107 SDLoc dl(Node); 9108 SDValue LHS = Node->getOperand(0); 9109 SDValue RHS = Node->getOperand(1); 9110 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9111 9112 // If ADD/SUBCARRY is legal, use that instead. 9113 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9114 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9115 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9116 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9117 { LHS, RHS, CarryIn }); 9118 Result = SDValue(NodeCarry.getNode(), 0); 9119 Overflow = SDValue(NodeCarry.getNode(), 1); 9120 return; 9121 } 9122 9123 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9124 LHS.getValueType(), LHS, RHS); 9125 9126 EVT ResultType = Node->getValueType(1); 9127 EVT SetCCType = getSetCCResultType( 9128 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9129 SDValue SetCC; 9130 if (IsAdd && isOneConstant(RHS)) { 9131 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9132 // the live range of X. We assume comparing with 0 is cheap. 9133 // The general case (X + C) < C is not necessarily beneficial. Although we 9134 // reduce the live range of X, we may introduce the materialization of 9135 // constant C. 9136 SetCC = 9137 DAG.getSetCC(dl, SetCCType, Result, 9138 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9139 } else { 9140 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9141 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9142 } 9143 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9144 } 9145 9146 void TargetLowering::expandSADDSUBO( 9147 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9148 SDLoc dl(Node); 9149 SDValue LHS = Node->getOperand(0); 9150 SDValue RHS = Node->getOperand(1); 9151 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9152 9153 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9154 LHS.getValueType(), LHS, RHS); 9155 9156 EVT ResultType = Node->getValueType(1); 9157 EVT OType = getSetCCResultType( 9158 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9159 9160 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9161 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9162 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9163 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9164 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9165 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9166 return; 9167 } 9168 9169 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9170 9171 // For an addition, the result should be less than one of the operands (LHS) 9172 // if and only if the other operand (RHS) is negative, otherwise there will 9173 // be overflow. 9174 // For a subtraction, the result should be less than one of the operands 9175 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9176 // otherwise there will be overflow. 9177 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9178 SDValue ConditionRHS = 9179 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9180 9181 Overflow = DAG.getBoolExtOrTrunc( 9182 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9183 ResultType, ResultType); 9184 } 9185 9186 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9187 SDValue &Overflow, SelectionDAG &DAG) const { 9188 SDLoc dl(Node); 9189 EVT VT = Node->getValueType(0); 9190 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9191 SDValue LHS = Node->getOperand(0); 9192 SDValue RHS = Node->getOperand(1); 9193 bool isSigned = Node->getOpcode() == ISD::SMULO; 9194 9195 // For power-of-two multiplications we can use a simpler shift expansion. 9196 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9197 const APInt &C = RHSC->getAPIntValue(); 9198 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9199 if (C.isPowerOf2()) { 9200 // smulo(x, signed_min) is same as umulo(x, signed_min). 9201 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9202 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9203 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9204 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9205 Overflow = DAG.getSetCC(dl, SetCCVT, 9206 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9207 dl, VT, Result, ShiftAmt), 9208 LHS, ISD::SETNE); 9209 return true; 9210 } 9211 } 9212 9213 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9214 if (VT.isVector()) 9215 WideVT = 9216 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9217 9218 SDValue BottomHalf; 9219 SDValue TopHalf; 9220 static const unsigned Ops[2][3] = 9221 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9222 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9223 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9224 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9225 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9226 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9227 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9228 RHS); 9229 TopHalf = BottomHalf.getValue(1); 9230 } else if (isTypeLegal(WideVT)) { 9231 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9232 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9233 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9234 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9235 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9236 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9237 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9238 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9239 } else { 9240 if (VT.isVector()) 9241 return false; 9242 9243 // We can fall back to a libcall with an illegal type for the MUL if we 9244 // have a libcall big enough. 9245 // Also, we can fall back to a division in some cases, but that's a big 9246 // performance hit in the general case. 9247 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9248 if (WideVT == MVT::i16) 9249 LC = RTLIB::MUL_I16; 9250 else if (WideVT == MVT::i32) 9251 LC = RTLIB::MUL_I32; 9252 else if (WideVT == MVT::i64) 9253 LC = RTLIB::MUL_I64; 9254 else if (WideVT == MVT::i128) 9255 LC = RTLIB::MUL_I128; 9256 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9257 9258 SDValue HiLHS; 9259 SDValue HiRHS; 9260 if (isSigned) { 9261 // The high part is obtained by SRA'ing all but one of the bits of low 9262 // part. 9263 unsigned LoSize = VT.getFixedSizeInBits(); 9264 HiLHS = 9265 DAG.getNode(ISD::SRA, dl, VT, LHS, 9266 DAG.getConstant(LoSize - 1, dl, 9267 getPointerTy(DAG.getDataLayout()))); 9268 HiRHS = 9269 DAG.getNode(ISD::SRA, dl, VT, RHS, 9270 DAG.getConstant(LoSize - 1, dl, 9271 getPointerTy(DAG.getDataLayout()))); 9272 } else { 9273 HiLHS = DAG.getConstant(0, dl, VT); 9274 HiRHS = DAG.getConstant(0, dl, VT); 9275 } 9276 9277 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9278 // pre-lowered to the correct types. This all depends upon WideVT not 9279 // being a legal type for the architecture and thus has to be split to 9280 // two arguments. 9281 SDValue Ret; 9282 TargetLowering::MakeLibCallOptions CallOptions; 9283 CallOptions.setSExt(isSigned); 9284 CallOptions.setIsPostTypeLegalization(true); 9285 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9286 // Halves of WideVT are packed into registers in different order 9287 // depending on platform endianness. This is usually handled by 9288 // the C calling convention, but we can't defer to it in 9289 // the legalizer. 9290 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9291 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9292 } else { 9293 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9294 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9295 } 9296 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9297 "Ret value is a collection of constituent nodes holding result."); 9298 if (DAG.getDataLayout().isLittleEndian()) { 9299 // Same as above. 9300 BottomHalf = Ret.getOperand(0); 9301 TopHalf = Ret.getOperand(1); 9302 } else { 9303 BottomHalf = Ret.getOperand(1); 9304 TopHalf = Ret.getOperand(0); 9305 } 9306 } 9307 9308 Result = BottomHalf; 9309 if (isSigned) { 9310 SDValue ShiftAmt = DAG.getConstant( 9311 VT.getScalarSizeInBits() - 1, dl, 9312 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9313 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9314 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9315 } else { 9316 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9317 DAG.getConstant(0, dl, VT), ISD::SETNE); 9318 } 9319 9320 // Truncate the result if SetCC returns a larger type than needed. 9321 EVT RType = Node->getValueType(1); 9322 if (RType.bitsLT(Overflow.getValueType())) 9323 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9324 9325 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9326 "Unexpected result type for S/UMULO legalization"); 9327 return true; 9328 } 9329 9330 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9331 SDLoc dl(Node); 9332 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9333 SDValue Op = Node->getOperand(0); 9334 EVT VT = Op.getValueType(); 9335 9336 if (VT.isScalableVector()) 9337 report_fatal_error( 9338 "Expanding reductions for scalable vectors is undefined."); 9339 9340 // Try to use a shuffle reduction for power of two vectors. 9341 if (VT.isPow2VectorType()) { 9342 while (VT.getVectorNumElements() > 1) { 9343 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9344 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9345 break; 9346 9347 SDValue Lo, Hi; 9348 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9349 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9350 VT = HalfVT; 9351 } 9352 } 9353 9354 EVT EltVT = VT.getVectorElementType(); 9355 unsigned NumElts = VT.getVectorNumElements(); 9356 9357 SmallVector<SDValue, 8> Ops; 9358 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9359 9360 SDValue Res = Ops[0]; 9361 for (unsigned i = 1; i < NumElts; i++) 9362 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9363 9364 // Result type may be wider than element type. 9365 if (EltVT != Node->getValueType(0)) 9366 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9367 return Res; 9368 } 9369 9370 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9371 SDLoc dl(Node); 9372 SDValue AccOp = Node->getOperand(0); 9373 SDValue VecOp = Node->getOperand(1); 9374 SDNodeFlags Flags = Node->getFlags(); 9375 9376 EVT VT = VecOp.getValueType(); 9377 EVT EltVT = VT.getVectorElementType(); 9378 9379 if (VT.isScalableVector()) 9380 report_fatal_error( 9381 "Expanding reductions for scalable vectors is undefined."); 9382 9383 unsigned NumElts = VT.getVectorNumElements(); 9384 9385 SmallVector<SDValue, 8> Ops; 9386 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9387 9388 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9389 9390 SDValue Res = AccOp; 9391 for (unsigned i = 0; i < NumElts; i++) 9392 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9393 9394 return Res; 9395 } 9396 9397 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9398 SelectionDAG &DAG) const { 9399 EVT VT = Node->getValueType(0); 9400 SDLoc dl(Node); 9401 bool isSigned = Node->getOpcode() == ISD::SREM; 9402 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9403 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9404 SDValue Dividend = Node->getOperand(0); 9405 SDValue Divisor = Node->getOperand(1); 9406 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9407 SDVTList VTs = DAG.getVTList(VT, VT); 9408 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9409 return true; 9410 } 9411 if (isOperationLegalOrCustom(DivOpc, VT)) { 9412 // X % Y -> X-X/Y*Y 9413 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9414 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9415 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9416 return true; 9417 } 9418 return false; 9419 } 9420 9421 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9422 SelectionDAG &DAG) const { 9423 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9424 SDLoc dl(SDValue(Node, 0)); 9425 SDValue Src = Node->getOperand(0); 9426 9427 // DstVT is the result type, while SatVT is the size to which we saturate 9428 EVT SrcVT = Src.getValueType(); 9429 EVT DstVT = Node->getValueType(0); 9430 9431 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9432 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9433 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9434 assert(SatWidth <= DstWidth && 9435 "Expected saturation width smaller than result width"); 9436 9437 // Determine minimum and maximum integer values and their corresponding 9438 // floating-point values. 9439 APInt MinInt, MaxInt; 9440 if (IsSigned) { 9441 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9442 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9443 } else { 9444 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9445 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9446 } 9447 9448 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9449 // libcall emission cannot handle this. Large result types will fail. 9450 if (SrcVT == MVT::f16) { 9451 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9452 SrcVT = Src.getValueType(); 9453 } 9454 9455 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9456 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9457 9458 APFloat::opStatus MinStatus = 9459 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9460 APFloat::opStatus MaxStatus = 9461 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9462 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9463 !(MaxStatus & APFloat::opStatus::opInexact); 9464 9465 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9466 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9467 9468 // If the integer bounds are exactly representable as floats and min/max are 9469 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9470 // of comparisons and selects. 9471 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9472 isOperationLegal(ISD::FMAXNUM, SrcVT); 9473 if (AreExactFloatBounds && MinMaxLegal) { 9474 SDValue Clamped = Src; 9475 9476 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9477 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9478 // Clamp by MaxFloat from above. NaN cannot occur. 9479 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9480 // Convert clamped value to integer. 9481 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9482 dl, DstVT, Clamped); 9483 9484 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9485 // which will cast to zero. 9486 if (!IsSigned) 9487 return FpToInt; 9488 9489 // Otherwise, select 0 if Src is NaN. 9490 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9491 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9492 ISD::CondCode::SETUO); 9493 } 9494 9495 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9496 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9497 9498 // Result of direct conversion. The assumption here is that the operation is 9499 // non-trapping and it's fine to apply it to an out-of-range value if we 9500 // select it away later. 9501 SDValue FpToInt = 9502 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9503 9504 SDValue Select = FpToInt; 9505 9506 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9507 // MinInt if Src is NaN. 9508 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9509 ISD::CondCode::SETULT); 9510 // If Src OGT MaxFloat, select MaxInt. 9511 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9512 ISD::CondCode::SETOGT); 9513 9514 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9515 // is already zero. 9516 if (!IsSigned) 9517 return Select; 9518 9519 // Otherwise, select 0 if Src is NaN. 9520 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9521 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9522 } 9523 9524 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9525 SelectionDAG &DAG) const { 9526 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9527 assert(Node->getValueType(0).isScalableVector() && 9528 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9529 9530 EVT VT = Node->getValueType(0); 9531 SDValue V1 = Node->getOperand(0); 9532 SDValue V2 = Node->getOperand(1); 9533 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9534 SDLoc DL(Node); 9535 9536 // Expand through memory thusly: 9537 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9538 // Store V1, Ptr 9539 // Store V2, Ptr + sizeof(V1) 9540 // If (Imm < 0) 9541 // TrailingElts = -Imm 9542 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9543 // else 9544 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9545 // Res = Load Ptr 9546 9547 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9548 9549 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9550 VT.getVectorElementCount() * 2); 9551 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9552 EVT PtrVT = StackPtr.getValueType(); 9553 auto &MF = DAG.getMachineFunction(); 9554 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9555 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9556 9557 // Store the lo part of CONCAT_VECTORS(V1, V2) 9558 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9559 // Store the hi part of CONCAT_VECTORS(V1, V2) 9560 SDValue OffsetToV2 = DAG.getVScale( 9561 DL, PtrVT, 9562 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9563 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9564 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9565 9566 if (Imm >= 0) { 9567 // Load back the required element. getVectorElementPointer takes care of 9568 // clamping the index if it's out-of-bounds. 9569 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9570 // Load the spliced result 9571 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9572 MachinePointerInfo::getUnknownStack(MF)); 9573 } 9574 9575 uint64_t TrailingElts = -Imm; 9576 9577 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9578 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9579 SDValue TrailingBytes = 9580 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9581 9582 if (TrailingElts > VT.getVectorMinNumElements()) { 9583 SDValue VLBytes = DAG.getVScale( 9584 DL, PtrVT, 9585 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9586 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9587 } 9588 9589 // Calculate the start address of the spliced result. 9590 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9591 9592 // Load the spliced result 9593 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9594 MachinePointerInfo::getUnknownStack(MF)); 9595 } 9596 9597 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9598 SDValue &LHS, SDValue &RHS, 9599 SDValue &CC, SDValue Mask, 9600 SDValue EVL, bool &NeedInvert, 9601 const SDLoc &dl, SDValue &Chain, 9602 bool IsSignaling) const { 9603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9604 MVT OpVT = LHS.getSimpleValueType(); 9605 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9606 NeedInvert = false; 9607 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9608 bool IsNonVP = !EVL; 9609 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9610 default: 9611 llvm_unreachable("Unknown condition code action!"); 9612 case TargetLowering::Legal: 9613 // Nothing to do. 9614 break; 9615 case TargetLowering::Expand: { 9616 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9617 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9618 std::swap(LHS, RHS); 9619 CC = DAG.getCondCode(InvCC); 9620 return true; 9621 } 9622 // Swapping operands didn't work. Try inverting the condition. 9623 bool NeedSwap = false; 9624 InvCC = getSetCCInverse(CCCode, OpVT); 9625 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9626 // If inverting the condition is not enough, try swapping operands 9627 // on top of it. 9628 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9629 NeedSwap = true; 9630 } 9631 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9632 CC = DAG.getCondCode(InvCC); 9633 NeedInvert = true; 9634 if (NeedSwap) 9635 std::swap(LHS, RHS); 9636 return true; 9637 } 9638 9639 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9640 unsigned Opc = 0; 9641 switch (CCCode) { 9642 default: 9643 llvm_unreachable("Don't know how to expand this condition!"); 9644 case ISD::SETUO: 9645 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9646 CC1 = ISD::SETUNE; 9647 CC2 = ISD::SETUNE; 9648 Opc = ISD::OR; 9649 break; 9650 } 9651 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9652 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9653 NeedInvert = true; 9654 LLVM_FALLTHROUGH; 9655 case ISD::SETO: 9656 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9657 "If SETO is expanded, SETOEQ must be legal!"); 9658 CC1 = ISD::SETOEQ; 9659 CC2 = ISD::SETOEQ; 9660 Opc = ISD::AND; 9661 break; 9662 case ISD::SETONE: 9663 case ISD::SETUEQ: 9664 // If the SETUO or SETO CC isn't legal, we might be able to use 9665 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9666 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9667 // the operands. 9668 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9669 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9670 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9671 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9672 CC1 = ISD::SETOGT; 9673 CC2 = ISD::SETOLT; 9674 Opc = ISD::OR; 9675 NeedInvert = ((unsigned)CCCode & 0x8U); 9676 break; 9677 } 9678 LLVM_FALLTHROUGH; 9679 case ISD::SETOEQ: 9680 case ISD::SETOGT: 9681 case ISD::SETOGE: 9682 case ISD::SETOLT: 9683 case ISD::SETOLE: 9684 case ISD::SETUNE: 9685 case ISD::SETUGT: 9686 case ISD::SETUGE: 9687 case ISD::SETULT: 9688 case ISD::SETULE: 9689 // If we are floating point, assign and break, otherwise fall through. 9690 if (!OpVT.isInteger()) { 9691 // We can use the 4th bit to tell if we are the unordered 9692 // or ordered version of the opcode. 9693 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9694 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9695 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9696 break; 9697 } 9698 // Fallthrough if we are unsigned integer. 9699 LLVM_FALLTHROUGH; 9700 case ISD::SETLE: 9701 case ISD::SETGT: 9702 case ISD::SETGE: 9703 case ISD::SETLT: 9704 case ISD::SETNE: 9705 case ISD::SETEQ: 9706 // If all combinations of inverting the condition and swapping operands 9707 // didn't work then we have no means to expand the condition. 9708 llvm_unreachable("Don't know how to expand this condition!"); 9709 } 9710 9711 SDValue SetCC1, SetCC2; 9712 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9713 // If we aren't the ordered or unorder operation, 9714 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9715 if (IsNonVP) { 9716 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9717 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9718 } else { 9719 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9720 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9721 } 9722 } else { 9723 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9724 if (IsNonVP) { 9725 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9726 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9727 } else { 9728 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9729 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9730 } 9731 } 9732 if (Chain) 9733 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9734 SetCC2.getValue(1)); 9735 if (IsNonVP) 9736 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9737 else { 9738 // Transform the binary opcode to the VP equivalent. 9739 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9740 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9741 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9742 } 9743 RHS = SDValue(); 9744 CC = SDValue(); 9745 return true; 9746 } 9747 } 9748 return false; 9749 } 9750