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 EVT VT = Op.getValueType(); 1060 if (VT.isScalableVector()) 1061 return false; 1062 1063 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1064 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1065 assert((!VT.isVector() || NumElts == VT.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 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 1092 if (Depth != 0) { 1093 // If not at the root, Just compute the Known bits to 1094 // simplify things downstream. 1095 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1096 return false; 1097 } 1098 // If this is the root being simplified, allow it to have multiple uses, 1099 // just set the DemandedBits/Elts to all bits. 1100 DemandedBits = APInt::getAllOnes(BitWidth); 1101 DemandedElts = APInt::getAllOnes(NumElts); 1102 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1103 // Not demanding any bits/elts from Op. 1104 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1105 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1106 // Limit search depth. 1107 return false; 1108 } 1109 1110 KnownBits Known2; 1111 switch (Op.getOpcode()) { 1112 case ISD::TargetConstant: 1113 llvm_unreachable("Can't simplify this node"); 1114 case ISD::SCALAR_TO_VECTOR: { 1115 if (!DemandedElts[0]) 1116 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1117 1118 KnownBits SrcKnown; 1119 SDValue Src = Op.getOperand(0); 1120 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1121 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1122 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1123 return true; 1124 1125 // Upper elements are undef, so only get the knownbits if we just demand 1126 // the bottom element. 1127 if (DemandedElts == 1) 1128 Known = SrcKnown.anyextOrTrunc(BitWidth); 1129 break; 1130 } 1131 case ISD::BUILD_VECTOR: 1132 // Collect the known bits that are shared by every demanded element. 1133 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1134 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1135 return false; // Don't fall through, will infinitely loop. 1136 case ISD::LOAD: { 1137 auto *LD = cast<LoadSDNode>(Op); 1138 if (getTargetConstantFromLoad(LD)) { 1139 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1140 return false; // Don't fall through, will infinitely loop. 1141 } 1142 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1143 // If this is a ZEXTLoad and we are looking at the loaded value. 1144 EVT MemVT = LD->getMemoryVT(); 1145 unsigned MemBits = MemVT.getScalarSizeInBits(); 1146 Known.Zero.setBitsFrom(MemBits); 1147 return false; // Don't fall through, will infinitely loop. 1148 } 1149 break; 1150 } 1151 case ISD::INSERT_VECTOR_ELT: { 1152 SDValue Vec = Op.getOperand(0); 1153 SDValue Scl = Op.getOperand(1); 1154 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1155 EVT VecVT = Vec.getValueType(); 1156 1157 // If index isn't constant, assume we need all vector elements AND the 1158 // inserted element. 1159 APInt DemandedVecElts(DemandedElts); 1160 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1161 unsigned Idx = CIdx->getZExtValue(); 1162 DemandedVecElts.clearBit(Idx); 1163 1164 // Inserted element is not required. 1165 if (!DemandedElts[Idx]) 1166 return TLO.CombineTo(Op, Vec); 1167 } 1168 1169 KnownBits KnownScl; 1170 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1171 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1172 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1173 return true; 1174 1175 Known = KnownScl.anyextOrTrunc(BitWidth); 1176 1177 KnownBits KnownVec; 1178 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1179 Depth + 1)) 1180 return true; 1181 1182 if (!!DemandedVecElts) 1183 Known = KnownBits::commonBits(Known, KnownVec); 1184 1185 return false; 1186 } 1187 case ISD::INSERT_SUBVECTOR: { 1188 // Demand any elements from the subvector and the remainder from the src its 1189 // inserted into. 1190 SDValue Src = Op.getOperand(0); 1191 SDValue Sub = Op.getOperand(1); 1192 uint64_t Idx = Op.getConstantOperandVal(2); 1193 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1194 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1195 APInt DemandedSrcElts = DemandedElts; 1196 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1197 1198 KnownBits KnownSub, KnownSrc; 1199 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1200 Depth + 1)) 1201 return true; 1202 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1203 Depth + 1)) 1204 return true; 1205 1206 Known.Zero.setAllBits(); 1207 Known.One.setAllBits(); 1208 if (!!DemandedSubElts) 1209 Known = KnownBits::commonBits(Known, KnownSub); 1210 if (!!DemandedSrcElts) 1211 Known = KnownBits::commonBits(Known, KnownSrc); 1212 1213 // Attempt to avoid multi-use src if we don't need anything from it. 1214 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1215 !DemandedSrcElts.isAllOnes()) { 1216 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1217 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1218 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1219 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1220 if (NewSub || NewSrc) { 1221 NewSub = NewSub ? NewSub : Sub; 1222 NewSrc = NewSrc ? NewSrc : Src; 1223 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1224 Op.getOperand(2)); 1225 return TLO.CombineTo(Op, NewOp); 1226 } 1227 } 1228 break; 1229 } 1230 case ISD::EXTRACT_SUBVECTOR: { 1231 // Offset the demanded elts by the subvector index. 1232 SDValue Src = Op.getOperand(0); 1233 if (Src.getValueType().isScalableVector()) 1234 break; 1235 uint64_t Idx = Op.getConstantOperandVal(1); 1236 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1237 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1238 1239 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1240 Depth + 1)) 1241 return true; 1242 1243 // Attempt to avoid multi-use src if we don't need anything from it. 1244 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1245 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1246 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1247 if (DemandedSrc) { 1248 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1249 Op.getOperand(1)); 1250 return TLO.CombineTo(Op, NewOp); 1251 } 1252 } 1253 break; 1254 } 1255 case ISD::CONCAT_VECTORS: { 1256 Known.Zero.setAllBits(); 1257 Known.One.setAllBits(); 1258 EVT SubVT = Op.getOperand(0).getValueType(); 1259 unsigned NumSubVecs = Op.getNumOperands(); 1260 unsigned NumSubElts = SubVT.getVectorNumElements(); 1261 for (unsigned i = 0; i != NumSubVecs; ++i) { 1262 APInt DemandedSubElts = 1263 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1264 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1265 Known2, TLO, Depth + 1)) 1266 return true; 1267 // Known bits are shared by every demanded subvector element. 1268 if (!!DemandedSubElts) 1269 Known = KnownBits::commonBits(Known, Known2); 1270 } 1271 break; 1272 } 1273 case ISD::VECTOR_SHUFFLE: { 1274 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1275 1276 // Collect demanded elements from shuffle operands.. 1277 APInt DemandedLHS(NumElts, 0); 1278 APInt DemandedRHS(NumElts, 0); 1279 for (unsigned i = 0; i != NumElts; ++i) { 1280 if (!DemandedElts[i]) 1281 continue; 1282 int M = ShuffleMask[i]; 1283 if (M < 0) { 1284 // For UNDEF elements, we don't know anything about the common state of 1285 // the shuffle result. 1286 DemandedLHS.clearAllBits(); 1287 DemandedRHS.clearAllBits(); 1288 break; 1289 } 1290 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1291 if (M < (int)NumElts) 1292 DemandedLHS.setBit(M); 1293 else 1294 DemandedRHS.setBit(M - NumElts); 1295 } 1296 1297 if (!!DemandedLHS || !!DemandedRHS) { 1298 SDValue Op0 = Op.getOperand(0); 1299 SDValue Op1 = Op.getOperand(1); 1300 1301 Known.Zero.setAllBits(); 1302 Known.One.setAllBits(); 1303 if (!!DemandedLHS) { 1304 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1305 Depth + 1)) 1306 return true; 1307 Known = KnownBits::commonBits(Known, Known2); 1308 } 1309 if (!!DemandedRHS) { 1310 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1311 Depth + 1)) 1312 return true; 1313 Known = KnownBits::commonBits(Known, Known2); 1314 } 1315 1316 // Attempt to avoid multi-use ops if we don't need anything from them. 1317 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1318 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1319 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1320 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1321 if (DemandedOp0 || DemandedOp1) { 1322 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1323 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1324 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1325 return TLO.CombineTo(Op, NewOp); 1326 } 1327 } 1328 break; 1329 } 1330 case ISD::AND: { 1331 SDValue Op0 = Op.getOperand(0); 1332 SDValue Op1 = Op.getOperand(1); 1333 1334 // If the RHS is a constant, check to see if the LHS would be zero without 1335 // using the bits from the RHS. Below, we use knowledge about the RHS to 1336 // simplify the LHS, here we're using information from the LHS to simplify 1337 // the RHS. 1338 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1339 // Do not increment Depth here; that can cause an infinite loop. 1340 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1341 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1342 if ((LHSKnown.Zero & DemandedBits) == 1343 (~RHSC->getAPIntValue() & DemandedBits)) 1344 return TLO.CombineTo(Op, Op0); 1345 1346 // If any of the set bits in the RHS are known zero on the LHS, shrink 1347 // the constant. 1348 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1349 DemandedElts, TLO)) 1350 return true; 1351 1352 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1353 // constant, but if this 'and' is only clearing bits that were just set by 1354 // the xor, then this 'and' can be eliminated by shrinking the mask of 1355 // the xor. For example, for a 32-bit X: 1356 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1357 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1358 LHSKnown.One == ~RHSC->getAPIntValue()) { 1359 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1360 return TLO.CombineTo(Op, Xor); 1361 } 1362 } 1363 1364 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1365 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1366 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && 1367 (Op0.getOperand(0).isUndef() || 1368 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1369 Op0->hasOneUse()) { 1370 unsigned NumSubElts = 1371 Op0.getOperand(1).getValueType().getVectorNumElements(); 1372 unsigned SubIdx = Op0.getConstantOperandVal(2); 1373 APInt DemandedSub = 1374 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1375 KnownBits KnownSubMask = 1376 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1377 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1378 SDValue NewAnd = 1379 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1380 SDValue NewInsert = 1381 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1382 Op0.getOperand(1), Op0.getOperand(2)); 1383 return TLO.CombineTo(Op, NewInsert); 1384 } 1385 } 1386 1387 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1388 Depth + 1)) 1389 return true; 1390 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1391 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1392 Known2, TLO, Depth + 1)) 1393 return true; 1394 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1395 1396 // If all of the demanded bits are known one on one side, return the other. 1397 // These bits cannot contribute to the result of the 'and'. 1398 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1399 return TLO.CombineTo(Op, Op0); 1400 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1401 return TLO.CombineTo(Op, Op1); 1402 // If all of the demanded bits in the inputs are known zeros, return zero. 1403 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1404 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1405 // If the RHS is a constant, see if we can simplify it. 1406 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1407 TLO)) 1408 return true; 1409 // If the operation can be done in a smaller type, do so. 1410 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1411 return true; 1412 1413 // Attempt to avoid multi-use ops if we don't need anything from them. 1414 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1415 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1416 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1417 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1418 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1419 if (DemandedOp0 || DemandedOp1) { 1420 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1421 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1422 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1423 return TLO.CombineTo(Op, NewOp); 1424 } 1425 } 1426 1427 Known &= Known2; 1428 break; 1429 } 1430 case ISD::OR: { 1431 SDValue Op0 = Op.getOperand(0); 1432 SDValue Op1 = Op.getOperand(1); 1433 1434 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1435 Depth + 1)) 1436 return true; 1437 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1438 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1439 Known2, TLO, Depth + 1)) 1440 return true; 1441 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1442 1443 // If all of the demanded bits are known zero on one side, return the other. 1444 // These bits cannot contribute to the result of the 'or'. 1445 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1446 return TLO.CombineTo(Op, Op0); 1447 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1448 return TLO.CombineTo(Op, Op1); 1449 // If the RHS is a constant, see if we can simplify it. 1450 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1451 return true; 1452 // If the operation can be done in a smaller type, do so. 1453 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1454 return true; 1455 1456 // Attempt to avoid multi-use ops if we don't need anything from them. 1457 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1458 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1459 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1460 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1461 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1462 if (DemandedOp0 || DemandedOp1) { 1463 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1464 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1465 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1466 return TLO.CombineTo(Op, NewOp); 1467 } 1468 } 1469 1470 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2)) 1471 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks. 1472 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND && 1473 Op0->hasOneUse() && Op1->hasOneUse()) { 1474 // Attempt to match all commutations - m_c_Or would've been useful! 1475 for (int I = 0; I != 2; ++I) { 1476 SDValue X = Op.getOperand(I).getOperand(0); 1477 SDValue C1 = Op.getOperand(I).getOperand(1); 1478 SDValue Alt = Op.getOperand(1 - I).getOperand(0); 1479 SDValue C2 = Op.getOperand(1 - I).getOperand(1); 1480 if (Alt.getOpcode() == ISD::OR) { 1481 for (int J = 0; J != 2; ++J) { 1482 if (X == Alt.getOperand(J)) { 1483 SDValue Y = Alt.getOperand(1 - J); 1484 if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, 1485 {C1, C2})) { 1486 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12); 1487 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2); 1488 return TLO.CombineTo( 1489 Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY)); 1490 } 1491 } 1492 } 1493 } 1494 } 1495 } 1496 1497 Known |= Known2; 1498 break; 1499 } 1500 case ISD::XOR: { 1501 SDValue Op0 = Op.getOperand(0); 1502 SDValue Op1 = Op.getOperand(1); 1503 1504 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1505 Depth + 1)) 1506 return true; 1507 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1508 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1509 Depth + 1)) 1510 return true; 1511 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1512 1513 // If all of the demanded bits are known zero on one side, return the other. 1514 // These bits cannot contribute to the result of the 'xor'. 1515 if (DemandedBits.isSubsetOf(Known.Zero)) 1516 return TLO.CombineTo(Op, Op0); 1517 if (DemandedBits.isSubsetOf(Known2.Zero)) 1518 return TLO.CombineTo(Op, Op1); 1519 // If the operation can be done in a smaller type, do so. 1520 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1521 return true; 1522 1523 // If all of the unknown bits are known to be zero on one side or the other 1524 // turn this into an *inclusive* or. 1525 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1526 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1527 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1528 1529 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts); 1530 if (C) { 1531 // If one side is a constant, and all of the set bits in the constant are 1532 // also known set on the other side, turn this into an AND, as we know 1533 // the bits will be cleared. 1534 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1535 // NB: it is okay if more bits are known than are requested 1536 if (C->getAPIntValue() == Known2.One) { 1537 SDValue ANDC = 1538 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1539 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1540 } 1541 1542 // If the RHS is a constant, see if we can change it. Don't alter a -1 1543 // constant because that's a 'not' op, and that is better for combining 1544 // and codegen. 1545 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1546 // We're flipping all demanded bits. Flip the undemanded bits too. 1547 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1548 return TLO.CombineTo(Op, New); 1549 } 1550 1551 unsigned Op0Opcode = Op0.getOpcode(); 1552 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) { 1553 if (ConstantSDNode *ShiftC = 1554 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) { 1555 // Don't crash on an oversized shift. We can not guarantee that a 1556 // bogus shift has been simplified to undef. 1557 if (ShiftC->getAPIntValue().ult(BitWidth)) { 1558 uint64_t ShiftAmt = ShiftC->getZExtValue(); 1559 APInt Ones = APInt::getAllOnes(BitWidth); 1560 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) 1561 : Ones.lshr(ShiftAmt); 1562 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 1563 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) && 1564 TLI.isDesirableToCommuteXorWithShift(Op.getNode())) { 1565 // If the xor constant is a demanded mask, do a 'not' before the 1566 // shift: 1567 // xor (X << ShiftC), XorC --> (not X) << ShiftC 1568 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 1569 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT); 1570 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not, 1571 Op0.getOperand(1))); 1572 } 1573 } 1574 } 1575 } 1576 } 1577 1578 // If we can't turn this into a 'not', try to shrink the constant. 1579 if (!C || !C->isAllOnes()) 1580 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1581 return true; 1582 1583 // Attempt to avoid multi-use ops if we don't need anything from them. 1584 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1585 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1586 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1587 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1588 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1589 if (DemandedOp0 || DemandedOp1) { 1590 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1591 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1592 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1593 return TLO.CombineTo(Op, NewOp); 1594 } 1595 } 1596 1597 Known ^= Known2; 1598 break; 1599 } 1600 case ISD::SELECT: 1601 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1602 Depth + 1)) 1603 return true; 1604 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1605 Depth + 1)) 1606 return true; 1607 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1608 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1609 1610 // If the operands are constants, see if we can simplify them. 1611 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1612 return true; 1613 1614 // Only known if known in both the LHS and RHS. 1615 Known = KnownBits::commonBits(Known, Known2); 1616 break; 1617 case ISD::VSELECT: 1618 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1619 Known, TLO, Depth + 1)) 1620 return true; 1621 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1622 Known2, TLO, Depth + 1)) 1623 return true; 1624 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1625 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1626 1627 // Only known if known in both the LHS and RHS. 1628 Known = KnownBits::commonBits(Known, Known2); 1629 break; 1630 case ISD::SELECT_CC: 1631 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1632 Depth + 1)) 1633 return true; 1634 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1635 Depth + 1)) 1636 return true; 1637 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1638 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1639 1640 // If the operands are constants, see if we can simplify them. 1641 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1642 return true; 1643 1644 // Only known if known in both the LHS and RHS. 1645 Known = KnownBits::commonBits(Known, Known2); 1646 break; 1647 case ISD::SETCC: { 1648 SDValue Op0 = Op.getOperand(0); 1649 SDValue Op1 = Op.getOperand(1); 1650 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1651 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1652 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1653 // -1, we may be able to bypass the setcc. 1654 if (DemandedBits.isSignMask() && 1655 Op0.getScalarValueSizeInBits() == BitWidth && 1656 getBooleanContents(Op0.getValueType()) == 1657 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1658 // If we're testing X < 0, then this compare isn't needed - just use X! 1659 // FIXME: We're limiting to integer types here, but this should also work 1660 // if we don't care about FP signed-zero. The use of SETLT with FP means 1661 // that we don't care about NaNs. 1662 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1663 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1664 return TLO.CombineTo(Op, Op0); 1665 1666 // TODO: Should we check for other forms of sign-bit comparisons? 1667 // Examples: X <= -1, X >= 0 1668 } 1669 if (getBooleanContents(Op0.getValueType()) == 1670 TargetLowering::ZeroOrOneBooleanContent && 1671 BitWidth > 1) 1672 Known.Zero.setBitsFrom(1); 1673 break; 1674 } 1675 case ISD::SHL: { 1676 SDValue Op0 = Op.getOperand(0); 1677 SDValue Op1 = Op.getOperand(1); 1678 EVT ShiftVT = Op1.getValueType(); 1679 1680 if (const APInt *SA = 1681 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1682 unsigned ShAmt = SA->getZExtValue(); 1683 if (ShAmt == 0) 1684 return TLO.CombineTo(Op, Op0); 1685 1686 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1687 // single shift. We can do this if the bottom bits (which are shifted 1688 // out) are never demanded. 1689 // TODO - support non-uniform vector amounts. 1690 if (Op0.getOpcode() == ISD::SRL) { 1691 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1692 if (const APInt *SA2 = 1693 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1694 unsigned C1 = SA2->getZExtValue(); 1695 unsigned Opc = ISD::SHL; 1696 int Diff = ShAmt - C1; 1697 if (Diff < 0) { 1698 Diff = -Diff; 1699 Opc = ISD::SRL; 1700 } 1701 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1702 return TLO.CombineTo( 1703 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1704 } 1705 } 1706 } 1707 1708 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1709 // are not demanded. This will likely allow the anyext to be folded away. 1710 // TODO - support non-uniform vector amounts. 1711 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1712 SDValue InnerOp = Op0.getOperand(0); 1713 EVT InnerVT = InnerOp.getValueType(); 1714 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1715 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1716 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1717 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1718 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1719 ShTy = InnerVT; 1720 SDValue NarrowShl = 1721 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1722 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1723 return TLO.CombineTo( 1724 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1725 } 1726 1727 // Repeat the SHL optimization above in cases where an extension 1728 // intervenes: (shl (anyext (shr x, c1)), c2) to 1729 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1730 // aren't demanded (as above) and that the shifted upper c1 bits of 1731 // x aren't demanded. 1732 // TODO - support non-uniform vector amounts. 1733 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1734 InnerOp.hasOneUse()) { 1735 if (const APInt *SA2 = 1736 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1737 unsigned InnerShAmt = SA2->getZExtValue(); 1738 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1739 DemandedBits.getActiveBits() <= 1740 (InnerBits - InnerShAmt + ShAmt) && 1741 DemandedBits.countTrailingZeros() >= ShAmt) { 1742 SDValue NewSA = 1743 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1744 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1745 InnerOp.getOperand(0)); 1746 return TLO.CombineTo( 1747 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1748 } 1749 } 1750 } 1751 } 1752 1753 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1754 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1755 Depth + 1)) 1756 return true; 1757 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1758 Known.Zero <<= ShAmt; 1759 Known.One <<= ShAmt; 1760 // low bits known zero. 1761 Known.Zero.setLowBits(ShAmt); 1762 1763 // Attempt to avoid multi-use ops if we don't need anything from them. 1764 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1765 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1766 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1767 if (DemandedOp0) { 1768 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1769 return TLO.CombineTo(Op, NewOp); 1770 } 1771 } 1772 1773 // Try shrinking the operation as long as the shift amount will still be 1774 // in range. 1775 if ((ShAmt < DemandedBits.getActiveBits()) && 1776 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1777 return true; 1778 } else { 1779 // This is a variable shift, so we can't shift the demand mask by a known 1780 // amount. But if we are not demanding high bits, then we are not 1781 // demanding those bits from the pre-shifted operand either. 1782 if (unsigned CTLZ = DemandedBits.countLeadingZeros()) { 1783 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1784 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1785 Depth + 1)) { 1786 SDNodeFlags Flags = Op.getNode()->getFlags(); 1787 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1788 // Disable the nsw and nuw flags. We can no longer guarantee that we 1789 // won't wrap after simplification. 1790 Flags.setNoSignedWrap(false); 1791 Flags.setNoUnsignedWrap(false); 1792 Op->setFlags(Flags); 1793 } 1794 return true; 1795 } 1796 Known.resetAll(); 1797 } 1798 } 1799 1800 // If we are only demanding sign bits then we can use the shift source 1801 // directly. 1802 if (const APInt *MaxSA = 1803 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1804 unsigned ShAmt = MaxSA->getZExtValue(); 1805 unsigned NumSignBits = 1806 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1807 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1808 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1809 return TLO.CombineTo(Op, Op0); 1810 } 1811 break; 1812 } 1813 case ISD::SRL: { 1814 SDValue Op0 = Op.getOperand(0); 1815 SDValue Op1 = Op.getOperand(1); 1816 EVT ShiftVT = Op1.getValueType(); 1817 1818 // Try to match AVG patterns. 1819 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1820 DemandedElts, Depth + 1)) 1821 return TLO.CombineTo(Op, AVG); 1822 1823 if (const APInt *SA = 1824 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1825 unsigned ShAmt = SA->getZExtValue(); 1826 if (ShAmt == 0) 1827 return TLO.CombineTo(Op, Op0); 1828 1829 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1830 // single shift. We can do this if the top bits (which are shifted out) 1831 // are never demanded. 1832 // TODO - support non-uniform vector amounts. 1833 if (Op0.getOpcode() == ISD::SHL) { 1834 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1835 if (const APInt *SA2 = 1836 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1837 unsigned C1 = SA2->getZExtValue(); 1838 unsigned Opc = ISD::SRL; 1839 int Diff = ShAmt - C1; 1840 if (Diff < 0) { 1841 Diff = -Diff; 1842 Opc = ISD::SHL; 1843 } 1844 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1845 return TLO.CombineTo( 1846 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1847 } 1848 } 1849 } 1850 1851 APInt InDemandedMask = (DemandedBits << ShAmt); 1852 1853 // If the shift is exact, then it does demand the low bits (and knows that 1854 // they are zero). 1855 if (Op->getFlags().hasExact()) 1856 InDemandedMask.setLowBits(ShAmt); 1857 1858 // Compute the new bits that are at the top now. 1859 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1860 Depth + 1)) 1861 return true; 1862 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1863 Known.Zero.lshrInPlace(ShAmt); 1864 Known.One.lshrInPlace(ShAmt); 1865 // High bits known zero. 1866 Known.Zero.setHighBits(ShAmt); 1867 } 1868 break; 1869 } 1870 case ISD::SRA: { 1871 SDValue Op0 = Op.getOperand(0); 1872 SDValue Op1 = Op.getOperand(1); 1873 EVT ShiftVT = Op1.getValueType(); 1874 1875 // If we only want bits that already match the signbit then we don't need 1876 // to shift. 1877 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1878 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1879 NumHiDemandedBits) 1880 return TLO.CombineTo(Op, Op0); 1881 1882 // If this is an arithmetic shift right and only the low-bit is set, we can 1883 // always convert this into a logical shr, even if the shift amount is 1884 // variable. The low bit of the shift cannot be an input sign bit unless 1885 // the shift amount is >= the size of the datatype, which is undefined. 1886 if (DemandedBits.isOne()) 1887 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1888 1889 // Try to match AVG patterns. 1890 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1891 DemandedElts, Depth + 1)) 1892 return TLO.CombineTo(Op, AVG); 1893 1894 if (const APInt *SA = 1895 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1896 unsigned ShAmt = SA->getZExtValue(); 1897 if (ShAmt == 0) 1898 return TLO.CombineTo(Op, Op0); 1899 1900 APInt InDemandedMask = (DemandedBits << ShAmt); 1901 1902 // If the shift is exact, then it does demand the low bits (and knows that 1903 // they are zero). 1904 if (Op->getFlags().hasExact()) 1905 InDemandedMask.setLowBits(ShAmt); 1906 1907 // If any of the demanded bits are produced by the sign extension, we also 1908 // demand the input sign bit. 1909 if (DemandedBits.countLeadingZeros() < ShAmt) 1910 InDemandedMask.setSignBit(); 1911 1912 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1913 Depth + 1)) 1914 return true; 1915 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1916 Known.Zero.lshrInPlace(ShAmt); 1917 Known.One.lshrInPlace(ShAmt); 1918 1919 // If the input sign bit is known to be zero, or if none of the top bits 1920 // are demanded, turn this into an unsigned shift right. 1921 if (Known.Zero[BitWidth - ShAmt - 1] || 1922 DemandedBits.countLeadingZeros() >= ShAmt) { 1923 SDNodeFlags Flags; 1924 Flags.setExact(Op->getFlags().hasExact()); 1925 return TLO.CombineTo( 1926 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1927 } 1928 1929 int Log2 = DemandedBits.exactLogBase2(); 1930 if (Log2 >= 0) { 1931 // The bit must come from the sign. 1932 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1933 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1934 } 1935 1936 if (Known.One[BitWidth - ShAmt - 1]) 1937 // New bits are known one. 1938 Known.One.setHighBits(ShAmt); 1939 1940 // Attempt to avoid multi-use ops if we don't need anything from them. 1941 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1942 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1943 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1944 if (DemandedOp0) { 1945 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1946 return TLO.CombineTo(Op, NewOp); 1947 } 1948 } 1949 } 1950 break; 1951 } 1952 case ISD::FSHL: 1953 case ISD::FSHR: { 1954 SDValue Op0 = Op.getOperand(0); 1955 SDValue Op1 = Op.getOperand(1); 1956 SDValue Op2 = Op.getOperand(2); 1957 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1958 1959 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1960 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1961 1962 // For fshl, 0-shift returns the 1st arg. 1963 // For fshr, 0-shift returns the 2nd arg. 1964 if (Amt == 0) { 1965 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1966 Known, TLO, Depth + 1)) 1967 return true; 1968 break; 1969 } 1970 1971 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1972 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1973 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1974 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1975 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1976 Depth + 1)) 1977 return true; 1978 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1979 Depth + 1)) 1980 return true; 1981 1982 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1983 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1984 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1985 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1986 Known.One |= Known2.One; 1987 Known.Zero |= Known2.Zero; 1988 1989 // Attempt to avoid multi-use ops if we don't need anything from them. 1990 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 1991 !DemandedElts.isAllOnes()) { 1992 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1993 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 1994 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1995 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 1996 if (DemandedOp0 || DemandedOp1) { 1997 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 1998 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 1999 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 2000 DemandedOp1, Op2); 2001 return TLO.CombineTo(Op, NewOp); 2002 } 2003 } 2004 } 2005 2006 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2007 if (isPowerOf2_32(BitWidth)) { 2008 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 2009 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 2010 Known2, TLO, Depth + 1)) 2011 return true; 2012 } 2013 break; 2014 } 2015 case ISD::ROTL: 2016 case ISD::ROTR: { 2017 SDValue Op0 = Op.getOperand(0); 2018 SDValue Op1 = Op.getOperand(1); 2019 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 2020 2021 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 2022 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 2023 return TLO.CombineTo(Op, Op0); 2024 2025 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 2026 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2027 unsigned RevAmt = BitWidth - Amt; 2028 2029 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 2030 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 2031 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 2032 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2033 Depth + 1)) 2034 return true; 2035 2036 // rot*(x, 0) --> x 2037 if (Amt == 0) 2038 return TLO.CombineTo(Op, Op0); 2039 2040 // See if we don't demand either half of the rotated bits. 2041 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 2042 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 2043 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 2044 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 2045 } 2046 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 2047 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 2048 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 2049 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2050 } 2051 } 2052 2053 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2054 if (isPowerOf2_32(BitWidth)) { 2055 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2056 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2057 Depth + 1)) 2058 return true; 2059 } 2060 break; 2061 } 2062 case ISD::UMIN: { 2063 // Check if one arg is always less than (or equal) to the other arg. 2064 SDValue Op0 = Op.getOperand(0); 2065 SDValue Op1 = Op.getOperand(1); 2066 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2067 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2068 Known = KnownBits::umin(Known0, Known1); 2069 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2070 return TLO.CombineTo(Op, IsULE.value() ? Op0 : Op1); 2071 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2072 return TLO.CombineTo(Op, IsULT.value() ? Op0 : Op1); 2073 break; 2074 } 2075 case ISD::UMAX: { 2076 // Check if one arg is always greater than (or equal) to the other arg. 2077 SDValue Op0 = Op.getOperand(0); 2078 SDValue Op1 = Op.getOperand(1); 2079 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2080 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2081 Known = KnownBits::umax(Known0, Known1); 2082 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2083 return TLO.CombineTo(Op, IsUGE.value() ? Op0 : Op1); 2084 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2085 return TLO.CombineTo(Op, IsUGT.value() ? Op0 : Op1); 2086 break; 2087 } 2088 case ISD::BITREVERSE: { 2089 SDValue Src = Op.getOperand(0); 2090 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2091 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2092 Depth + 1)) 2093 return true; 2094 Known.One = Known2.One.reverseBits(); 2095 Known.Zero = Known2.Zero.reverseBits(); 2096 break; 2097 } 2098 case ISD::BSWAP: { 2099 SDValue Src = Op.getOperand(0); 2100 2101 // If the only bits demanded come from one byte of the bswap result, 2102 // just shift the input byte into position to eliminate the bswap. 2103 unsigned NLZ = DemandedBits.countLeadingZeros(); 2104 unsigned NTZ = DemandedBits.countTrailingZeros(); 2105 2106 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2107 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2108 // have 14 leading zeros, round to 8. 2109 NLZ = alignDown(NLZ, 8); 2110 NTZ = alignDown(NTZ, 8); 2111 // If we need exactly one byte, we can do this transformation. 2112 if (BitWidth - NLZ - NTZ == 8) { 2113 // Replace this with either a left or right shift to get the byte into 2114 // the right place. 2115 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2116 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2117 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2118 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2119 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2120 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2121 return TLO.CombineTo(Op, NewOp); 2122 } 2123 } 2124 2125 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2126 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2127 Depth + 1)) 2128 return true; 2129 Known.One = Known2.One.byteSwap(); 2130 Known.Zero = Known2.Zero.byteSwap(); 2131 break; 2132 } 2133 case ISD::CTPOP: { 2134 // If only 1 bit is demanded, replace with PARITY as long as we're before 2135 // op legalization. 2136 // FIXME: Limit to scalars for now. 2137 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2138 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2139 Op.getOperand(0))); 2140 2141 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2142 break; 2143 } 2144 case ISD::SIGN_EXTEND_INREG: { 2145 SDValue Op0 = Op.getOperand(0); 2146 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2147 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2148 2149 // If we only care about the highest bit, don't bother shifting right. 2150 if (DemandedBits.isSignMask()) { 2151 unsigned MinSignedBits = 2152 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2153 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2154 // However if the input is already sign extended we expect the sign 2155 // extension to be dropped altogether later and do not simplify. 2156 if (!AlreadySignExtended) { 2157 // Compute the correct shift amount type, which must be getShiftAmountTy 2158 // for scalar types after legalization. 2159 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2160 getShiftAmountTy(VT, DL)); 2161 return TLO.CombineTo(Op, 2162 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2163 } 2164 } 2165 2166 // If none of the extended bits are demanded, eliminate the sextinreg. 2167 if (DemandedBits.getActiveBits() <= ExVTBits) 2168 return TLO.CombineTo(Op, Op0); 2169 2170 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2171 2172 // Since the sign extended bits are demanded, we know that the sign 2173 // bit is demanded. 2174 InputDemandedBits.setBit(ExVTBits - 1); 2175 2176 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2177 Depth + 1)) 2178 return true; 2179 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2180 2181 // If the sign bit of the input is known set or clear, then we know the 2182 // top bits of the result. 2183 2184 // If the input sign bit is known zero, convert this into a zero extension. 2185 if (Known.Zero[ExVTBits - 1]) 2186 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2187 2188 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2189 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2190 Known.One.setBitsFrom(ExVTBits); 2191 Known.Zero &= Mask; 2192 } else { // Input sign bit unknown 2193 Known.Zero &= Mask; 2194 Known.One &= Mask; 2195 } 2196 break; 2197 } 2198 case ISD::BUILD_PAIR: { 2199 EVT HalfVT = Op.getOperand(0).getValueType(); 2200 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2201 2202 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2203 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2204 2205 KnownBits KnownLo, KnownHi; 2206 2207 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2208 return true; 2209 2210 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2211 return true; 2212 2213 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2214 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2215 2216 Known.One = KnownLo.One.zext(BitWidth) | 2217 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2218 break; 2219 } 2220 case ISD::ZERO_EXTEND: 2221 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2222 SDValue Src = Op.getOperand(0); 2223 EVT SrcVT = Src.getValueType(); 2224 unsigned InBits = SrcVT.getScalarSizeInBits(); 2225 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2226 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2227 2228 // If none of the top bits are demanded, convert this into an any_extend. 2229 if (DemandedBits.getActiveBits() <= InBits) { 2230 // If we only need the non-extended bits of the bottom element 2231 // then we can just bitcast to the result. 2232 if (IsLE && IsVecInReg && DemandedElts == 1 && 2233 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2234 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2235 2236 unsigned Opc = 2237 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2238 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2239 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2240 } 2241 2242 APInt InDemandedBits = DemandedBits.trunc(InBits); 2243 APInt InDemandedElts = DemandedElts.zext(InElts); 2244 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2245 Depth + 1)) 2246 return true; 2247 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2248 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2249 Known = Known.zext(BitWidth); 2250 2251 // Attempt to avoid multi-use ops if we don't need anything from them. 2252 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2253 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2254 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2255 break; 2256 } 2257 case ISD::SIGN_EXTEND: 2258 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2259 SDValue Src = Op.getOperand(0); 2260 EVT SrcVT = Src.getValueType(); 2261 unsigned InBits = SrcVT.getScalarSizeInBits(); 2262 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2263 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2264 2265 // If none of the top bits are demanded, convert this into an any_extend. 2266 if (DemandedBits.getActiveBits() <= InBits) { 2267 // If we only need the non-extended bits of the bottom element 2268 // then we can just bitcast to the result. 2269 if (IsLE && IsVecInReg && DemandedElts == 1 && 2270 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2271 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2272 2273 unsigned Opc = 2274 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2275 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2276 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2277 } 2278 2279 APInt InDemandedBits = DemandedBits.trunc(InBits); 2280 APInt InDemandedElts = DemandedElts.zext(InElts); 2281 2282 // Since some of the sign extended bits are demanded, we know that the sign 2283 // bit is demanded. 2284 InDemandedBits.setBit(InBits - 1); 2285 2286 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2287 Depth + 1)) 2288 return true; 2289 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2290 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2291 2292 // If the sign bit is known one, the top bits match. 2293 Known = Known.sext(BitWidth); 2294 2295 // If the sign bit is known zero, convert this to a zero extend. 2296 if (Known.isNonNegative()) { 2297 unsigned Opc = 2298 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2299 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2300 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2301 } 2302 2303 // Attempt to avoid multi-use ops if we don't need anything from them. 2304 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2305 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2306 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2307 break; 2308 } 2309 case ISD::ANY_EXTEND: 2310 case ISD::ANY_EXTEND_VECTOR_INREG: { 2311 SDValue Src = Op.getOperand(0); 2312 EVT SrcVT = Src.getValueType(); 2313 unsigned InBits = SrcVT.getScalarSizeInBits(); 2314 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2315 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2316 2317 // If we only need the bottom element then we can just bitcast. 2318 // TODO: Handle ANY_EXTEND? 2319 if (IsLE && IsVecInReg && DemandedElts == 1 && 2320 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2321 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2322 2323 APInt InDemandedBits = DemandedBits.trunc(InBits); 2324 APInt InDemandedElts = DemandedElts.zext(InElts); 2325 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2326 Depth + 1)) 2327 return true; 2328 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2329 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2330 Known = Known.anyext(BitWidth); 2331 2332 // Attempt to avoid multi-use ops if we don't need anything from them. 2333 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2334 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2335 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2336 break; 2337 } 2338 case ISD::TRUNCATE: { 2339 SDValue Src = Op.getOperand(0); 2340 2341 // Simplify the input, using demanded bit information, and compute the known 2342 // zero/one bits live out. 2343 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2344 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2345 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2346 Depth + 1)) 2347 return true; 2348 Known = Known.trunc(BitWidth); 2349 2350 // Attempt to avoid multi-use ops if we don't need anything from them. 2351 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2352 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2353 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2354 2355 // If the input is only used by this truncate, see if we can shrink it based 2356 // on the known demanded bits. 2357 if (Src.getNode()->hasOneUse()) { 2358 switch (Src.getOpcode()) { 2359 default: 2360 break; 2361 case ISD::SRL: 2362 // Shrink SRL by a constant if none of the high bits shifted in are 2363 // demanded. 2364 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2365 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2366 // undesirable. 2367 break; 2368 2369 const APInt *ShAmtC = 2370 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2371 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2372 break; 2373 uint64_t ShVal = ShAmtC->getZExtValue(); 2374 2375 APInt HighBits = 2376 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2377 HighBits.lshrInPlace(ShVal); 2378 HighBits = HighBits.trunc(BitWidth); 2379 2380 if (!(HighBits & DemandedBits)) { 2381 // None of the shifted in bits are needed. Add a truncate of the 2382 // shift input, then shift it. 2383 SDValue NewShAmt = TLO.DAG.getConstant( 2384 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2385 SDValue NewTrunc = 2386 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2387 return TLO.CombineTo( 2388 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2389 } 2390 break; 2391 } 2392 } 2393 2394 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2395 break; 2396 } 2397 case ISD::AssertZext: { 2398 // AssertZext demands all of the high bits, plus any of the low bits 2399 // demanded by its users. 2400 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2401 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2402 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2403 TLO, Depth + 1)) 2404 return true; 2405 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2406 2407 Known.Zero |= ~InMask; 2408 break; 2409 } 2410 case ISD::EXTRACT_VECTOR_ELT: { 2411 SDValue Src = Op.getOperand(0); 2412 SDValue Idx = Op.getOperand(1); 2413 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2414 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2415 2416 if (SrcEltCnt.isScalable()) 2417 return false; 2418 2419 // Demand the bits from every vector element without a constant index. 2420 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2421 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2422 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2423 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2424 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2425 2426 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2427 // anything about the extended bits. 2428 APInt DemandedSrcBits = DemandedBits; 2429 if (BitWidth > EltBitWidth) 2430 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2431 2432 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2433 Depth + 1)) 2434 return true; 2435 2436 // Attempt to avoid multi-use ops if we don't need anything from them. 2437 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2438 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2439 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2440 SDValue NewOp = 2441 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2442 return TLO.CombineTo(Op, NewOp); 2443 } 2444 } 2445 2446 Known = Known2; 2447 if (BitWidth > EltBitWidth) 2448 Known = Known.anyext(BitWidth); 2449 break; 2450 } 2451 case ISD::BITCAST: { 2452 SDValue Src = Op.getOperand(0); 2453 EVT SrcVT = Src.getValueType(); 2454 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2455 2456 // If this is an FP->Int bitcast and if the sign bit is the only 2457 // thing demanded, turn this into a FGETSIGN. 2458 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2459 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2460 SrcVT.isFloatingPoint()) { 2461 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2462 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2463 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2464 SrcVT != MVT::f128) { 2465 // Cannot eliminate/lower SHL for f128 yet. 2466 EVT Ty = OpVTLegal ? VT : MVT::i32; 2467 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2468 // place. We expect the SHL to be eliminated by other optimizations. 2469 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2470 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2471 if (!OpVTLegal && OpVTSizeInBits > 32) 2472 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2473 unsigned ShVal = Op.getValueSizeInBits() - 1; 2474 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2475 return TLO.CombineTo(Op, 2476 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2477 } 2478 } 2479 2480 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2481 // Demand the elt/bit if any of the original elts/bits are demanded. 2482 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2483 unsigned Scale = BitWidth / NumSrcEltBits; 2484 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2485 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2486 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2487 for (unsigned i = 0; i != Scale; ++i) { 2488 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2489 unsigned BitOffset = EltOffset * NumSrcEltBits; 2490 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2491 if (!Sub.isZero()) { 2492 DemandedSrcBits |= Sub; 2493 for (unsigned j = 0; j != NumElts; ++j) 2494 if (DemandedElts[j]) 2495 DemandedSrcElts.setBit((j * Scale) + i); 2496 } 2497 } 2498 2499 APInt KnownSrcUndef, KnownSrcZero; 2500 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2501 KnownSrcZero, TLO, Depth + 1)) 2502 return true; 2503 2504 KnownBits KnownSrcBits; 2505 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2506 KnownSrcBits, TLO, Depth + 1)) 2507 return true; 2508 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2509 // TODO - bigendian once we have test coverage. 2510 unsigned Scale = NumSrcEltBits / BitWidth; 2511 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2512 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2513 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2514 for (unsigned i = 0; i != NumElts; ++i) 2515 if (DemandedElts[i]) { 2516 unsigned Offset = (i % Scale) * BitWidth; 2517 DemandedSrcBits.insertBits(DemandedBits, Offset); 2518 DemandedSrcElts.setBit(i / Scale); 2519 } 2520 2521 if (SrcVT.isVector()) { 2522 APInt KnownSrcUndef, KnownSrcZero; 2523 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2524 KnownSrcZero, TLO, Depth + 1)) 2525 return true; 2526 } 2527 2528 KnownBits KnownSrcBits; 2529 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2530 KnownSrcBits, TLO, Depth + 1)) 2531 return true; 2532 } 2533 2534 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2535 // recursive call where Known may be useful to the caller. 2536 if (Depth > 0) { 2537 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2538 return false; 2539 } 2540 break; 2541 } 2542 case ISD::MUL: 2543 if (DemandedBits.isPowerOf2()) { 2544 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2545 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2546 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2547 unsigned CTZ = DemandedBits.countTrailingZeros(); 2548 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2549 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2550 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2551 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2552 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2553 return TLO.CombineTo(Op, Shl); 2554 } 2555 } 2556 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2557 // X * X is odd iff X is odd. 2558 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2559 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2560 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2561 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2562 return TLO.CombineTo(Op, And1); 2563 } 2564 LLVM_FALLTHROUGH; 2565 case ISD::ADD: 2566 case ISD::SUB: { 2567 // Add, Sub, and Mul don't demand any bits in positions beyond that 2568 // of the highest bit demanded of them. 2569 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2570 SDNodeFlags Flags = Op.getNode()->getFlags(); 2571 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2572 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2573 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2574 Depth + 1) || 2575 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2576 Depth + 1) || 2577 // See if the operation should be performed at a smaller bit width. 2578 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2579 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2580 // Disable the nsw and nuw flags. We can no longer guarantee that we 2581 // won't wrap after simplification. 2582 Flags.setNoSignedWrap(false); 2583 Flags.setNoUnsignedWrap(false); 2584 Op->setFlags(Flags); 2585 } 2586 return true; 2587 } 2588 2589 // Attempt to avoid multi-use ops if we don't need anything from them. 2590 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2591 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2592 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2593 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2594 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2595 if (DemandedOp0 || DemandedOp1) { 2596 Flags.setNoSignedWrap(false); 2597 Flags.setNoUnsignedWrap(false); 2598 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2599 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2600 SDValue NewOp = 2601 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2602 return TLO.CombineTo(Op, NewOp); 2603 } 2604 } 2605 2606 // If we have a constant operand, we may be able to turn it into -1 if we 2607 // do not demand the high bits. This can make the constant smaller to 2608 // encode, allow more general folding, or match specialized instruction 2609 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2610 // is probably not useful (and could be detrimental). 2611 ConstantSDNode *C = isConstOrConstSplat(Op1); 2612 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2613 if (C && !C->isAllOnes() && !C->isOne() && 2614 (C->getAPIntValue() | HighMask).isAllOnes()) { 2615 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2616 // Disable the nsw and nuw flags. We can no longer guarantee that we 2617 // won't wrap after simplification. 2618 Flags.setNoSignedWrap(false); 2619 Flags.setNoUnsignedWrap(false); 2620 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2621 return TLO.CombineTo(Op, NewOp); 2622 } 2623 2624 // Match a multiply with a disguised negated-power-of-2 and convert to a 2625 // an equivalent shift-left amount. 2626 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2627 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2628 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2629 return 0; 2630 2631 // Don't touch opaque constants. Also, ignore zero and power-of-2 2632 // multiplies. Those will get folded later. 2633 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2634 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2635 !MulC->getAPIntValue().isPowerOf2()) { 2636 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2637 if (UnmaskedC.isNegatedPowerOf2()) 2638 return (-UnmaskedC).logBase2(); 2639 } 2640 return 0; 2641 }; 2642 2643 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) { 2644 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2645 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2646 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2647 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2648 return TLO.CombineTo(Op, Res); 2649 }; 2650 2651 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2652 if (Op.getOpcode() == ISD::ADD) { 2653 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2654 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2655 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2656 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2657 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2658 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2659 } 2660 if (Op.getOpcode() == ISD::SUB) { 2661 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2662 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2663 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2664 } 2665 } 2666 2667 LLVM_FALLTHROUGH; 2668 } 2669 default: 2670 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2671 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2672 Known, TLO, Depth)) 2673 return true; 2674 break; 2675 } 2676 2677 // Just use computeKnownBits to compute output bits. 2678 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2679 break; 2680 } 2681 2682 // If we know the value of all of the demanded bits, return this as a 2683 // constant. 2684 if (!isTargetCanonicalConstantNode(Op) && 2685 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2686 // Avoid folding to a constant if any OpaqueConstant is involved. 2687 const SDNode *N = Op.getNode(); 2688 for (SDNode *Op : 2689 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2690 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2691 if (C->isOpaque()) 2692 return false; 2693 } 2694 if (VT.isInteger()) 2695 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2696 if (VT.isFloatingPoint()) 2697 return TLO.CombineTo( 2698 Op, 2699 TLO.DAG.getConstantFP( 2700 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2701 } 2702 2703 return false; 2704 } 2705 2706 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2707 const APInt &DemandedElts, 2708 DAGCombinerInfo &DCI) const { 2709 SelectionDAG &DAG = DCI.DAG; 2710 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2711 !DCI.isBeforeLegalizeOps()); 2712 2713 APInt KnownUndef, KnownZero; 2714 bool Simplified = 2715 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2716 if (Simplified) { 2717 DCI.AddToWorklist(Op.getNode()); 2718 DCI.CommitTargetLoweringOpt(TLO); 2719 } 2720 2721 return Simplified; 2722 } 2723 2724 /// Given a vector binary operation and known undefined elements for each input 2725 /// operand, compute whether each element of the output is undefined. 2726 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2727 const APInt &UndefOp0, 2728 const APInt &UndefOp1) { 2729 EVT VT = BO.getValueType(); 2730 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2731 "Vector binop only"); 2732 2733 EVT EltVT = VT.getVectorElementType(); 2734 unsigned NumElts = VT.getVectorNumElements(); 2735 assert(UndefOp0.getBitWidth() == NumElts && 2736 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2737 2738 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2739 const APInt &UndefVals) { 2740 if (UndefVals[Index]) 2741 return DAG.getUNDEF(EltVT); 2742 2743 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2744 // Try hard to make sure that the getNode() call is not creating temporary 2745 // nodes. Ignore opaque integers because they do not constant fold. 2746 SDValue Elt = BV->getOperand(Index); 2747 auto *C = dyn_cast<ConstantSDNode>(Elt); 2748 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2749 return Elt; 2750 } 2751 2752 return SDValue(); 2753 }; 2754 2755 APInt KnownUndef = APInt::getZero(NumElts); 2756 for (unsigned i = 0; i != NumElts; ++i) { 2757 // If both inputs for this element are either constant or undef and match 2758 // the element type, compute the constant/undef result for this element of 2759 // the vector. 2760 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2761 // not handle FP constants. The code within getNode() should be refactored 2762 // to avoid the danger of creating a bogus temporary node here. 2763 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2764 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2765 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2766 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2767 KnownUndef.setBit(i); 2768 } 2769 return KnownUndef; 2770 } 2771 2772 bool TargetLowering::SimplifyDemandedVectorElts( 2773 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2774 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2775 bool AssumeSingleUse) const { 2776 EVT VT = Op.getValueType(); 2777 unsigned Opcode = Op.getOpcode(); 2778 APInt DemandedElts = OriginalDemandedElts; 2779 unsigned NumElts = DemandedElts.getBitWidth(); 2780 assert(VT.isVector() && "Expected vector op"); 2781 2782 KnownUndef = KnownZero = APInt::getZero(NumElts); 2783 2784 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2785 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2786 return false; 2787 2788 // TODO: For now we assume we know nothing about scalable vectors. 2789 if (VT.isScalableVector()) 2790 return false; 2791 2792 assert(VT.getVectorNumElements() == NumElts && 2793 "Mask size mismatches value type element count!"); 2794 2795 // Undef operand. 2796 if (Op.isUndef()) { 2797 KnownUndef.setAllBits(); 2798 return false; 2799 } 2800 2801 // If Op has other users, assume that all elements are needed. 2802 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2803 DemandedElts.setAllBits(); 2804 2805 // Not demanding any elements from Op. 2806 if (DemandedElts == 0) { 2807 KnownUndef.setAllBits(); 2808 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2809 } 2810 2811 // Limit search depth. 2812 if (Depth >= SelectionDAG::MaxRecursionDepth) 2813 return false; 2814 2815 SDLoc DL(Op); 2816 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2817 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2818 2819 // Helper for demanding the specified elements and all the bits of both binary 2820 // operands. 2821 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2822 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2823 TLO.DAG, Depth + 1); 2824 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2825 TLO.DAG, Depth + 1); 2826 if (NewOp0 || NewOp1) { 2827 SDValue NewOp = TLO.DAG.getNode( 2828 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2829 return TLO.CombineTo(Op, NewOp); 2830 } 2831 return false; 2832 }; 2833 2834 switch (Opcode) { 2835 case ISD::SCALAR_TO_VECTOR: { 2836 if (!DemandedElts[0]) { 2837 KnownUndef.setAllBits(); 2838 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2839 } 2840 SDValue ScalarSrc = Op.getOperand(0); 2841 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2842 SDValue Src = ScalarSrc.getOperand(0); 2843 SDValue Idx = ScalarSrc.getOperand(1); 2844 EVT SrcVT = Src.getValueType(); 2845 2846 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2847 2848 if (SrcEltCnt.isScalable()) 2849 return false; 2850 2851 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2852 if (isNullConstant(Idx)) { 2853 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2854 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2855 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2856 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2857 TLO, Depth + 1)) 2858 return true; 2859 } 2860 } 2861 KnownUndef.setHighBits(NumElts - 1); 2862 break; 2863 } 2864 case ISD::BITCAST: { 2865 SDValue Src = Op.getOperand(0); 2866 EVT SrcVT = Src.getValueType(); 2867 2868 // We only handle vectors here. 2869 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2870 if (!SrcVT.isVector()) 2871 break; 2872 2873 // Fast handling of 'identity' bitcasts. 2874 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2875 if (NumSrcElts == NumElts) 2876 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2877 KnownZero, TLO, Depth + 1); 2878 2879 APInt SrcDemandedElts, SrcZero, SrcUndef; 2880 2881 // Bitcast from 'large element' src vector to 'small element' vector, we 2882 // must demand a source element if any DemandedElt maps to it. 2883 if ((NumElts % NumSrcElts) == 0) { 2884 unsigned Scale = NumElts / NumSrcElts; 2885 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2886 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2887 TLO, Depth + 1)) 2888 return true; 2889 2890 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2891 // of the large element. 2892 // TODO - bigendian once we have test coverage. 2893 if (IsLE) { 2894 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2895 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2896 for (unsigned i = 0; i != NumElts; ++i) 2897 if (DemandedElts[i]) { 2898 unsigned Ofs = (i % Scale) * EltSizeInBits; 2899 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2900 } 2901 2902 KnownBits Known; 2903 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2904 TLO, Depth + 1)) 2905 return true; 2906 2907 // The bitcast has split each wide element into a number of 2908 // narrow subelements. We have just computed the Known bits 2909 // for wide elements. See if element splitting results in 2910 // some subelements being zero. Only for demanded elements! 2911 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2912 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2913 .isAllOnes()) 2914 continue; 2915 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2916 unsigned Elt = Scale * SrcElt + SubElt; 2917 if (DemandedElts[Elt]) 2918 KnownZero.setBit(Elt); 2919 } 2920 } 2921 } 2922 2923 // If the src element is zero/undef then all the output elements will be - 2924 // only demanded elements are guaranteed to be correct. 2925 for (unsigned i = 0; i != NumSrcElts; ++i) { 2926 if (SrcDemandedElts[i]) { 2927 if (SrcZero[i]) 2928 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2929 if (SrcUndef[i]) 2930 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2931 } 2932 } 2933 } 2934 2935 // Bitcast from 'small element' src vector to 'large element' vector, we 2936 // demand all smaller source elements covered by the larger demanded element 2937 // of this vector. 2938 if ((NumSrcElts % NumElts) == 0) { 2939 unsigned Scale = NumSrcElts / NumElts; 2940 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2941 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2942 TLO, Depth + 1)) 2943 return true; 2944 2945 // If all the src elements covering an output element are zero/undef, then 2946 // the output element will be as well, assuming it was demanded. 2947 for (unsigned i = 0; i != NumElts; ++i) { 2948 if (DemandedElts[i]) { 2949 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2950 KnownZero.setBit(i); 2951 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2952 KnownUndef.setBit(i); 2953 } 2954 } 2955 } 2956 break; 2957 } 2958 case ISD::BUILD_VECTOR: { 2959 // Check all elements and simplify any unused elements with UNDEF. 2960 if (!DemandedElts.isAllOnes()) { 2961 // Don't simplify BROADCASTS. 2962 if (llvm::any_of(Op->op_values(), 2963 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2964 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2965 bool Updated = false; 2966 for (unsigned i = 0; i != NumElts; ++i) { 2967 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2968 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2969 KnownUndef.setBit(i); 2970 Updated = true; 2971 } 2972 } 2973 if (Updated) 2974 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2975 } 2976 } 2977 for (unsigned i = 0; i != NumElts; ++i) { 2978 SDValue SrcOp = Op.getOperand(i); 2979 if (SrcOp.isUndef()) { 2980 KnownUndef.setBit(i); 2981 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2982 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2983 KnownZero.setBit(i); 2984 } 2985 } 2986 break; 2987 } 2988 case ISD::CONCAT_VECTORS: { 2989 EVT SubVT = Op.getOperand(0).getValueType(); 2990 unsigned NumSubVecs = Op.getNumOperands(); 2991 unsigned NumSubElts = SubVT.getVectorNumElements(); 2992 for (unsigned i = 0; i != NumSubVecs; ++i) { 2993 SDValue SubOp = Op.getOperand(i); 2994 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2995 APInt SubUndef, SubZero; 2996 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2997 Depth + 1)) 2998 return true; 2999 KnownUndef.insertBits(SubUndef, i * NumSubElts); 3000 KnownZero.insertBits(SubZero, i * NumSubElts); 3001 } 3002 3003 // Attempt to avoid multi-use ops if we don't need anything from them. 3004 if (!DemandedElts.isAllOnes()) { 3005 bool FoundNewSub = false; 3006 SmallVector<SDValue, 2> DemandedSubOps; 3007 for (unsigned i = 0; i != NumSubVecs; ++i) { 3008 SDValue SubOp = Op.getOperand(i); 3009 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3010 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 3011 SubOp, SubElts, TLO.DAG, Depth + 1); 3012 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 3013 FoundNewSub = NewSubOp ? true : FoundNewSub; 3014 } 3015 if (FoundNewSub) { 3016 SDValue NewOp = 3017 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 3018 return TLO.CombineTo(Op, NewOp); 3019 } 3020 } 3021 break; 3022 } 3023 case ISD::INSERT_SUBVECTOR: { 3024 // Demand any elements from the subvector and the remainder from the src its 3025 // inserted into. 3026 SDValue Src = Op.getOperand(0); 3027 SDValue Sub = Op.getOperand(1); 3028 uint64_t Idx = Op.getConstantOperandVal(2); 3029 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3030 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3031 APInt DemandedSrcElts = DemandedElts; 3032 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3033 3034 APInt SubUndef, SubZero; 3035 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 3036 Depth + 1)) 3037 return true; 3038 3039 // If none of the src operand elements are demanded, replace it with undef. 3040 if (!DemandedSrcElts && !Src.isUndef()) 3041 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 3042 TLO.DAG.getUNDEF(VT), Sub, 3043 Op.getOperand(2))); 3044 3045 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 3046 TLO, Depth + 1)) 3047 return true; 3048 KnownUndef.insertBits(SubUndef, Idx); 3049 KnownZero.insertBits(SubZero, Idx); 3050 3051 // Attempt to avoid multi-use ops if we don't need anything from them. 3052 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3053 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3054 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3055 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3056 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3057 if (NewSrc || NewSub) { 3058 NewSrc = NewSrc ? NewSrc : Src; 3059 NewSub = NewSub ? NewSub : Sub; 3060 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3061 NewSub, Op.getOperand(2)); 3062 return TLO.CombineTo(Op, NewOp); 3063 } 3064 } 3065 break; 3066 } 3067 case ISD::EXTRACT_SUBVECTOR: { 3068 // Offset the demanded elts by the subvector index. 3069 SDValue Src = Op.getOperand(0); 3070 if (Src.getValueType().isScalableVector()) 3071 break; 3072 uint64_t Idx = Op.getConstantOperandVal(1); 3073 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3074 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3075 3076 APInt SrcUndef, SrcZero; 3077 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3078 Depth + 1)) 3079 return true; 3080 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3081 KnownZero = SrcZero.extractBits(NumElts, Idx); 3082 3083 // Attempt to avoid multi-use ops if we don't need anything from them. 3084 if (!DemandedElts.isAllOnes()) { 3085 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3086 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3087 if (NewSrc) { 3088 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3089 Op.getOperand(1)); 3090 return TLO.CombineTo(Op, NewOp); 3091 } 3092 } 3093 break; 3094 } 3095 case ISD::INSERT_VECTOR_ELT: { 3096 SDValue Vec = Op.getOperand(0); 3097 SDValue Scl = Op.getOperand(1); 3098 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3099 3100 // For a legal, constant insertion index, if we don't need this insertion 3101 // then strip it, else remove it from the demanded elts. 3102 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3103 unsigned Idx = CIdx->getZExtValue(); 3104 if (!DemandedElts[Idx]) 3105 return TLO.CombineTo(Op, Vec); 3106 3107 APInt DemandedVecElts(DemandedElts); 3108 DemandedVecElts.clearBit(Idx); 3109 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3110 KnownZero, TLO, Depth + 1)) 3111 return true; 3112 3113 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3114 3115 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3116 break; 3117 } 3118 3119 APInt VecUndef, VecZero; 3120 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3121 Depth + 1)) 3122 return true; 3123 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3124 break; 3125 } 3126 case ISD::VSELECT: { 3127 SDValue Sel = Op.getOperand(0); 3128 SDValue LHS = Op.getOperand(1); 3129 SDValue RHS = Op.getOperand(2); 3130 3131 // Try to transform the select condition based on the current demanded 3132 // elements. 3133 APInt UndefSel, UndefZero; 3134 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, UndefZero, TLO, 3135 Depth + 1)) 3136 return true; 3137 3138 // See if we can simplify either vselect operand. 3139 APInt DemandedLHS(DemandedElts); 3140 APInt DemandedRHS(DemandedElts); 3141 APInt UndefLHS, ZeroLHS; 3142 APInt UndefRHS, ZeroRHS; 3143 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3144 Depth + 1)) 3145 return true; 3146 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3147 Depth + 1)) 3148 return true; 3149 3150 KnownUndef = UndefLHS & UndefRHS; 3151 KnownZero = ZeroLHS & ZeroRHS; 3152 3153 // If we know that the selected element is always zero, we don't need the 3154 // select value element. 3155 APInt DemandedSel = DemandedElts & ~KnownZero; 3156 if (DemandedSel != DemandedElts) 3157 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, UndefZero, TLO, 3158 Depth + 1)) 3159 return true; 3160 3161 break; 3162 } 3163 case ISD::VECTOR_SHUFFLE: { 3164 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3165 3166 // Collect demanded elements from shuffle operands.. 3167 APInt DemandedLHS(NumElts, 0); 3168 APInt DemandedRHS(NumElts, 0); 3169 for (unsigned i = 0; i != NumElts; ++i) { 3170 int M = ShuffleMask[i]; 3171 if (M < 0 || !DemandedElts[i]) 3172 continue; 3173 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3174 if (M < (int)NumElts) 3175 DemandedLHS.setBit(M); 3176 else 3177 DemandedRHS.setBit(M - NumElts); 3178 } 3179 3180 // See if we can simplify either shuffle operand. 3181 APInt UndefLHS, ZeroLHS; 3182 APInt UndefRHS, ZeroRHS; 3183 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3184 ZeroLHS, TLO, Depth + 1)) 3185 return true; 3186 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3187 ZeroRHS, TLO, Depth + 1)) 3188 return true; 3189 3190 // Simplify mask using undef elements from LHS/RHS. 3191 bool Updated = false; 3192 bool IdentityLHS = true, IdentityRHS = true; 3193 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3194 for (unsigned i = 0; i != NumElts; ++i) { 3195 int &M = NewMask[i]; 3196 if (M < 0) 3197 continue; 3198 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3199 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3200 Updated = true; 3201 M = -1; 3202 } 3203 IdentityLHS &= (M < 0) || (M == (int)i); 3204 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3205 } 3206 3207 // Update legal shuffle masks based on demanded elements if it won't reduce 3208 // to Identity which can cause premature removal of the shuffle mask. 3209 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3210 SDValue LegalShuffle = 3211 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3212 NewMask, TLO.DAG); 3213 if (LegalShuffle) 3214 return TLO.CombineTo(Op, LegalShuffle); 3215 } 3216 3217 // Propagate undef/zero elements from LHS/RHS. 3218 for (unsigned i = 0; i != NumElts; ++i) { 3219 int M = ShuffleMask[i]; 3220 if (M < 0) { 3221 KnownUndef.setBit(i); 3222 } else if (M < (int)NumElts) { 3223 if (UndefLHS[M]) 3224 KnownUndef.setBit(i); 3225 if (ZeroLHS[M]) 3226 KnownZero.setBit(i); 3227 } else { 3228 if (UndefRHS[M - NumElts]) 3229 KnownUndef.setBit(i); 3230 if (ZeroRHS[M - NumElts]) 3231 KnownZero.setBit(i); 3232 } 3233 } 3234 break; 3235 } 3236 case ISD::ANY_EXTEND_VECTOR_INREG: 3237 case ISD::SIGN_EXTEND_VECTOR_INREG: 3238 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3239 APInt SrcUndef, SrcZero; 3240 SDValue Src = Op.getOperand(0); 3241 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3242 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3243 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3244 Depth + 1)) 3245 return true; 3246 KnownZero = SrcZero.zextOrTrunc(NumElts); 3247 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3248 3249 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3250 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3251 DemandedSrcElts == 1) { 3252 // aext - if we just need the bottom element then we can bitcast. 3253 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3254 } 3255 3256 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3257 // zext(undef) upper bits are guaranteed to be zero. 3258 if (DemandedElts.isSubsetOf(KnownUndef)) 3259 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3260 KnownUndef.clearAllBits(); 3261 3262 // zext - if we just need the bottom element then we can mask: 3263 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3264 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3265 Op->isOnlyUserOf(Src.getNode()) && 3266 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3267 SDLoc DL(Op); 3268 EVT SrcVT = Src.getValueType(); 3269 EVT SrcSVT = SrcVT.getScalarType(); 3270 SmallVector<SDValue> MaskElts; 3271 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3272 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3273 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3274 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3275 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3276 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3277 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3278 } 3279 } 3280 } 3281 break; 3282 } 3283 3284 // TODO: There are more binop opcodes that could be handled here - MIN, 3285 // MAX, saturated math, etc. 3286 case ISD::ADD: { 3287 SDValue Op0 = Op.getOperand(0); 3288 SDValue Op1 = Op.getOperand(1); 3289 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3290 APInt UndefLHS, ZeroLHS; 3291 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3292 Depth + 1, /*AssumeSingleUse*/ true)) 3293 return true; 3294 } 3295 LLVM_FALLTHROUGH; 3296 } 3297 case ISD::OR: 3298 case ISD::XOR: 3299 case ISD::SUB: 3300 case ISD::FADD: 3301 case ISD::FSUB: 3302 case ISD::FMUL: 3303 case ISD::FDIV: 3304 case ISD::FREM: { 3305 SDValue Op0 = Op.getOperand(0); 3306 SDValue Op1 = Op.getOperand(1); 3307 3308 APInt UndefRHS, ZeroRHS; 3309 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3310 Depth + 1)) 3311 return true; 3312 APInt UndefLHS, ZeroLHS; 3313 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3314 Depth + 1)) 3315 return true; 3316 3317 KnownZero = ZeroLHS & ZeroRHS; 3318 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3319 3320 // Attempt to avoid multi-use ops if we don't need anything from them. 3321 // TODO - use KnownUndef to relax the demandedelts? 3322 if (!DemandedElts.isAllOnes()) 3323 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3324 return true; 3325 break; 3326 } 3327 case ISD::SHL: 3328 case ISD::SRL: 3329 case ISD::SRA: 3330 case ISD::ROTL: 3331 case ISD::ROTR: { 3332 SDValue Op0 = Op.getOperand(0); 3333 SDValue Op1 = Op.getOperand(1); 3334 3335 APInt UndefRHS, ZeroRHS; 3336 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3337 Depth + 1)) 3338 return true; 3339 APInt UndefLHS, ZeroLHS; 3340 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3341 Depth + 1)) 3342 return true; 3343 3344 KnownZero = ZeroLHS; 3345 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3346 3347 // Attempt to avoid multi-use ops if we don't need anything from them. 3348 // TODO - use KnownUndef to relax the demandedelts? 3349 if (!DemandedElts.isAllOnes()) 3350 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3351 return true; 3352 break; 3353 } 3354 case ISD::MUL: 3355 case ISD::AND: { 3356 SDValue Op0 = Op.getOperand(0); 3357 SDValue Op1 = Op.getOperand(1); 3358 3359 APInt SrcUndef, SrcZero; 3360 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3361 Depth + 1)) 3362 return true; 3363 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3364 TLO, Depth + 1)) 3365 return true; 3366 3367 // If every element pair has a zero/undef then just fold to zero. 3368 // fold (and x, undef) -> 0 / (and x, 0) -> 0 3369 // fold (mul x, undef) -> 0 / (mul x, 0) -> 0 3370 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef)) 3371 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3372 3373 // If either side has a zero element, then the result element is zero, even 3374 // if the other is an UNDEF. 3375 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3376 // and then handle 'and' nodes with the rest of the binop opcodes. 3377 KnownZero |= SrcZero; 3378 KnownUndef &= SrcUndef; 3379 KnownUndef &= ~KnownZero; 3380 3381 // Attempt to avoid multi-use ops if we don't need anything from them. 3382 if (!DemandedElts.isAllOnes()) 3383 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3384 return true; 3385 break; 3386 } 3387 case ISD::TRUNCATE: 3388 case ISD::SIGN_EXTEND: 3389 case ISD::ZERO_EXTEND: 3390 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3391 KnownZero, TLO, Depth + 1)) 3392 return true; 3393 3394 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3395 // zext(undef) upper bits are guaranteed to be zero. 3396 if (DemandedElts.isSubsetOf(KnownUndef)) 3397 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3398 KnownUndef.clearAllBits(); 3399 } 3400 break; 3401 default: { 3402 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3403 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3404 KnownZero, TLO, Depth)) 3405 return true; 3406 } else { 3407 KnownBits Known; 3408 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3409 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3410 TLO, Depth, AssumeSingleUse)) 3411 return true; 3412 } 3413 break; 3414 } 3415 } 3416 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3417 3418 // Constant fold all undef cases. 3419 // TODO: Handle zero cases as well. 3420 if (DemandedElts.isSubsetOf(KnownUndef)) 3421 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3422 3423 return false; 3424 } 3425 3426 /// Determine which of the bits specified in Mask are known to be either zero or 3427 /// one and return them in the Known. 3428 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3429 KnownBits &Known, 3430 const APInt &DemandedElts, 3431 const SelectionDAG &DAG, 3432 unsigned Depth) const { 3433 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3434 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3435 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3436 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3437 "Should use MaskedValueIsZero if you don't know whether Op" 3438 " is a target node!"); 3439 Known.resetAll(); 3440 } 3441 3442 void TargetLowering::computeKnownBitsForTargetInstr( 3443 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3444 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3445 unsigned Depth) const { 3446 Known.resetAll(); 3447 } 3448 3449 void TargetLowering::computeKnownBitsForFrameIndex( 3450 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3451 // The low bits are known zero if the pointer is aligned. 3452 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3453 } 3454 3455 Align TargetLowering::computeKnownAlignForTargetInstr( 3456 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3457 unsigned Depth) const { 3458 return Align(1); 3459 } 3460 3461 /// This method can be implemented by targets that want to expose additional 3462 /// information about sign bits to the DAG Combiner. 3463 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3464 const APInt &, 3465 const SelectionDAG &, 3466 unsigned Depth) const { 3467 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3468 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3469 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3470 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3471 "Should use ComputeNumSignBits if you don't know whether Op" 3472 " is a target node!"); 3473 return 1; 3474 } 3475 3476 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3477 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3478 const MachineRegisterInfo &MRI, unsigned Depth) const { 3479 return 1; 3480 } 3481 3482 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3483 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3484 TargetLoweringOpt &TLO, 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 SimplifyDemandedVectorElts if you don't know whether Op" 3490 " is a target node!"); 3491 return false; 3492 } 3493 3494 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3495 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3496 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3497 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3498 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3499 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3500 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3501 "Should use SimplifyDemandedBits if you don't know whether Op" 3502 " is a target node!"); 3503 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3504 return false; 3505 } 3506 3507 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3508 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3509 SelectionDAG &DAG, unsigned Depth) const { 3510 assert( 3511 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3512 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3513 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3514 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3515 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3516 " is a target node!"); 3517 return SDValue(); 3518 } 3519 3520 SDValue 3521 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3522 SDValue N1, MutableArrayRef<int> Mask, 3523 SelectionDAG &DAG) const { 3524 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3525 if (!LegalMask) { 3526 std::swap(N0, N1); 3527 ShuffleVectorSDNode::commuteMask(Mask); 3528 LegalMask = isShuffleMaskLegal(Mask, VT); 3529 } 3530 3531 if (!LegalMask) 3532 return SDValue(); 3533 3534 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3535 } 3536 3537 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3538 return nullptr; 3539 } 3540 3541 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3542 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3543 bool PoisonOnly, unsigned Depth) const { 3544 assert( 3545 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3546 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3547 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3548 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3549 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3550 " is a target node!"); 3551 return false; 3552 } 3553 3554 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3555 const SelectionDAG &DAG, 3556 bool SNaN, 3557 unsigned Depth) const { 3558 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3559 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3560 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3561 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3562 "Should use isKnownNeverNaN if you don't know whether Op" 3563 " is a target node!"); 3564 return false; 3565 } 3566 3567 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3568 const APInt &DemandedElts, 3569 APInt &UndefElts, 3570 unsigned Depth) const { 3571 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3572 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3573 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3574 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3575 "Should use isSplatValue if you don't know whether Op" 3576 " is a target node!"); 3577 return false; 3578 } 3579 3580 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3581 // work with truncating build vectors and vectors with elements of less than 3582 // 8 bits. 3583 bool TargetLowering::isConstTrueVal(SDValue N) const { 3584 if (!N) 3585 return false; 3586 3587 unsigned EltWidth; 3588 APInt CVal; 3589 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3590 /*AllowTruncation=*/true)) { 3591 CVal = CN->getAPIntValue(); 3592 EltWidth = N.getValueType().getScalarSizeInBits(); 3593 } else 3594 return false; 3595 3596 // If this is a truncating splat, truncate the splat value. 3597 // Otherwise, we may fail to match the expected values below. 3598 if (EltWidth < CVal.getBitWidth()) 3599 CVal = CVal.trunc(EltWidth); 3600 3601 switch (getBooleanContents(N.getValueType())) { 3602 case UndefinedBooleanContent: 3603 return CVal[0]; 3604 case ZeroOrOneBooleanContent: 3605 return CVal.isOne(); 3606 case ZeroOrNegativeOneBooleanContent: 3607 return CVal.isAllOnes(); 3608 } 3609 3610 llvm_unreachable("Invalid boolean contents"); 3611 } 3612 3613 bool TargetLowering::isConstFalseVal(SDValue N) const { 3614 if (!N) 3615 return false; 3616 3617 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3618 if (!CN) { 3619 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3620 if (!BV) 3621 return false; 3622 3623 // Only interested in constant splats, we don't care about undef 3624 // elements in identifying boolean constants and getConstantSplatNode 3625 // returns NULL if all ops are undef; 3626 CN = BV->getConstantSplatNode(); 3627 if (!CN) 3628 return false; 3629 } 3630 3631 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3632 return !CN->getAPIntValue()[0]; 3633 3634 return CN->isZero(); 3635 } 3636 3637 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3638 bool SExt) const { 3639 if (VT == MVT::i1) 3640 return N->isOne(); 3641 3642 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3643 switch (Cnt) { 3644 case TargetLowering::ZeroOrOneBooleanContent: 3645 // An extended value of 1 is always true, unless its original type is i1, 3646 // in which case it will be sign extended to -1. 3647 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3648 case TargetLowering::UndefinedBooleanContent: 3649 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3650 return N->isAllOnes() && SExt; 3651 } 3652 llvm_unreachable("Unexpected enumeration."); 3653 } 3654 3655 /// This helper function of SimplifySetCC tries to optimize the comparison when 3656 /// either operand of the SetCC node is a bitwise-and instruction. 3657 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3658 ISD::CondCode Cond, const SDLoc &DL, 3659 DAGCombinerInfo &DCI) const { 3660 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3661 std::swap(N0, N1); 3662 3663 SelectionDAG &DAG = DCI.DAG; 3664 EVT OpVT = N0.getValueType(); 3665 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3666 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3667 return SDValue(); 3668 3669 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3670 // iff everything but LSB is known zero: 3671 if (Cond == ISD::SETNE && isNullConstant(N1) && 3672 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3673 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3674 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3675 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3676 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3677 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3678 } 3679 3680 // Match these patterns in any of their permutations: 3681 // (X & Y) == Y 3682 // (X & Y) != Y 3683 SDValue X, Y; 3684 if (N0.getOperand(0) == N1) { 3685 X = N0.getOperand(1); 3686 Y = N0.getOperand(0); 3687 } else if (N0.getOperand(1) == N1) { 3688 X = N0.getOperand(0); 3689 Y = N0.getOperand(1); 3690 } else { 3691 return SDValue(); 3692 } 3693 3694 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3695 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3696 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3697 // Note that where Y is variable and is known to have at most one bit set 3698 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3699 // equivalent when Y == 0. 3700 assert(OpVT.isInteger()); 3701 Cond = ISD::getSetCCInverse(Cond, OpVT); 3702 if (DCI.isBeforeLegalizeOps() || 3703 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3704 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3705 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3706 // If the target supports an 'and-not' or 'and-complement' logic operation, 3707 // try to use that to make a comparison operation more efficient. 3708 // But don't do this transform if the mask is a single bit because there are 3709 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3710 // 'rlwinm' on PPC). 3711 3712 // Bail out if the compare operand that we want to turn into a zero is 3713 // already a zero (otherwise, infinite loop). 3714 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3715 if (YConst && YConst->isZero()) 3716 return SDValue(); 3717 3718 // Transform this into: ~X & Y == 0. 3719 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3720 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3721 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3722 } 3723 3724 return SDValue(); 3725 } 3726 3727 /// There are multiple IR patterns that could be checking whether certain 3728 /// truncation of a signed number would be lossy or not. The pattern which is 3729 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3730 /// We are looking for the following pattern: (KeptBits is a constant) 3731 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3732 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3733 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3734 /// We will unfold it into the natural trunc+sext pattern: 3735 /// ((%x << C) a>> C) dstcond %x 3736 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3737 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3738 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3739 const SDLoc &DL) const { 3740 // We must be comparing with a constant. 3741 ConstantSDNode *C1; 3742 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3743 return SDValue(); 3744 3745 // N0 should be: add %x, (1 << (KeptBits-1)) 3746 if (N0->getOpcode() != ISD::ADD) 3747 return SDValue(); 3748 3749 // And we must be 'add'ing a constant. 3750 ConstantSDNode *C01; 3751 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3752 return SDValue(); 3753 3754 SDValue X = N0->getOperand(0); 3755 EVT XVT = X.getValueType(); 3756 3757 // Validate constants ... 3758 3759 APInt I1 = C1->getAPIntValue(); 3760 3761 ISD::CondCode NewCond; 3762 if (Cond == ISD::CondCode::SETULT) { 3763 NewCond = ISD::CondCode::SETEQ; 3764 } else if (Cond == ISD::CondCode::SETULE) { 3765 NewCond = ISD::CondCode::SETEQ; 3766 // But need to 'canonicalize' the constant. 3767 I1 += 1; 3768 } else if (Cond == ISD::CondCode::SETUGT) { 3769 NewCond = ISD::CondCode::SETNE; 3770 // But need to 'canonicalize' the constant. 3771 I1 += 1; 3772 } else if (Cond == ISD::CondCode::SETUGE) { 3773 NewCond = ISD::CondCode::SETNE; 3774 } else 3775 return SDValue(); 3776 3777 APInt I01 = C01->getAPIntValue(); 3778 3779 auto checkConstants = [&I1, &I01]() -> bool { 3780 // Both of them must be power-of-two, and the constant from setcc is bigger. 3781 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3782 }; 3783 3784 if (checkConstants()) { 3785 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3786 } else { 3787 // What if we invert constants? (and the target predicate) 3788 I1.negate(); 3789 I01.negate(); 3790 assert(XVT.isInteger()); 3791 NewCond = getSetCCInverse(NewCond, XVT); 3792 if (!checkConstants()) 3793 return SDValue(); 3794 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3795 } 3796 3797 // They are power-of-two, so which bit is set? 3798 const unsigned KeptBits = I1.logBase2(); 3799 const unsigned KeptBitsMinusOne = I01.logBase2(); 3800 3801 // Magic! 3802 if (KeptBits != (KeptBitsMinusOne + 1)) 3803 return SDValue(); 3804 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3805 3806 // We don't want to do this in every single case. 3807 SelectionDAG &DAG = DCI.DAG; 3808 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3809 XVT, KeptBits)) 3810 return SDValue(); 3811 3812 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3813 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3814 3815 // Unfold into: ((%x << C) a>> C) cond %x 3816 // Where 'cond' will be either 'eq' or 'ne'. 3817 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3818 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3819 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3820 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3821 3822 return T2; 3823 } 3824 3825 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3826 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3827 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3828 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3829 assert(isConstOrConstSplat(N1C) && 3830 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3831 "Should be a comparison with 0."); 3832 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3833 "Valid only for [in]equality comparisons."); 3834 3835 unsigned NewShiftOpcode; 3836 SDValue X, C, Y; 3837 3838 SelectionDAG &DAG = DCI.DAG; 3839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3840 3841 // Look for '(C l>>/<< Y)'. 3842 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3843 // The shift should be one-use. 3844 if (!V.hasOneUse()) 3845 return false; 3846 unsigned OldShiftOpcode = V.getOpcode(); 3847 switch (OldShiftOpcode) { 3848 case ISD::SHL: 3849 NewShiftOpcode = ISD::SRL; 3850 break; 3851 case ISD::SRL: 3852 NewShiftOpcode = ISD::SHL; 3853 break; 3854 default: 3855 return false; // must be a logical shift. 3856 } 3857 // We should be shifting a constant. 3858 // FIXME: best to use isConstantOrConstantVector(). 3859 C = V.getOperand(0); 3860 ConstantSDNode *CC = 3861 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3862 if (!CC) 3863 return false; 3864 Y = V.getOperand(1); 3865 3866 ConstantSDNode *XC = 3867 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3868 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3869 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3870 }; 3871 3872 // LHS of comparison should be an one-use 'and'. 3873 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3874 return SDValue(); 3875 3876 X = N0.getOperand(0); 3877 SDValue Mask = N0.getOperand(1); 3878 3879 // 'and' is commutative! 3880 if (!Match(Mask)) { 3881 std::swap(X, Mask); 3882 if (!Match(Mask)) 3883 return SDValue(); 3884 } 3885 3886 EVT VT = X.getValueType(); 3887 3888 // Produce: 3889 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3890 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3891 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3892 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3893 return T2; 3894 } 3895 3896 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3897 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3898 /// handle the commuted versions of these patterns. 3899 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3900 ISD::CondCode Cond, const SDLoc &DL, 3901 DAGCombinerInfo &DCI) const { 3902 unsigned BOpcode = N0.getOpcode(); 3903 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3904 "Unexpected binop"); 3905 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3906 3907 // (X + Y) == X --> Y == 0 3908 // (X - Y) == X --> Y == 0 3909 // (X ^ Y) == X --> Y == 0 3910 SelectionDAG &DAG = DCI.DAG; 3911 EVT OpVT = N0.getValueType(); 3912 SDValue X = N0.getOperand(0); 3913 SDValue Y = N0.getOperand(1); 3914 if (X == N1) 3915 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3916 3917 if (Y != N1) 3918 return SDValue(); 3919 3920 // (X + Y) == Y --> X == 0 3921 // (X ^ Y) == Y --> X == 0 3922 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3923 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3924 3925 // The shift would not be valid if the operands are boolean (i1). 3926 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3927 return SDValue(); 3928 3929 // (X - Y) == Y --> X == Y << 1 3930 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3931 !DCI.isBeforeLegalize()); 3932 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3933 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3934 if (!DCI.isCalledByLegalizer()) 3935 DCI.AddToWorklist(YShl1.getNode()); 3936 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3937 } 3938 3939 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3940 SDValue N0, const APInt &C1, 3941 ISD::CondCode Cond, const SDLoc &dl, 3942 SelectionDAG &DAG) { 3943 // Look through truncs that don't change the value of a ctpop. 3944 // FIXME: Add vector support? Need to be careful with setcc result type below. 3945 SDValue CTPOP = N0; 3946 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3947 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3948 CTPOP = N0.getOperand(0); 3949 3950 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3951 return SDValue(); 3952 3953 EVT CTVT = CTPOP.getValueType(); 3954 SDValue CTOp = CTPOP.getOperand(0); 3955 3956 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3957 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3958 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3959 return SDValue(); 3960 3961 // (ctpop x) u< 2 -> (x & x-1) == 0 3962 // (ctpop x) u> 1 -> (x & x-1) != 0 3963 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3964 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3965 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3966 return SDValue(); 3967 if (C1 == 0 && (Cond == ISD::SETULT)) 3968 return SDValue(); // This is handled elsewhere. 3969 3970 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3971 3972 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3973 SDValue Result = CTOp; 3974 for (unsigned i = 0; i < Passes; i++) { 3975 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3976 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3977 } 3978 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3979 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3980 } 3981 3982 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3983 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3984 // For scalars, keep CTPOP if it is legal or custom. 3985 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3986 return SDValue(); 3987 // This is based on X86's custom lowering for CTPOP which produces more 3988 // instructions than the expansion here. 3989 3990 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3991 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3992 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3993 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3994 assert(CTVT.isInteger()); 3995 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3996 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3997 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3998 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3999 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 4000 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 4001 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 4002 } 4003 4004 return SDValue(); 4005 } 4006 4007 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 4008 ISD::CondCode Cond, const SDLoc &dl, 4009 SelectionDAG &DAG) { 4010 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4011 return SDValue(); 4012 4013 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4014 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 4015 return SDValue(); 4016 4017 auto getRotateSource = [](SDValue X) { 4018 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 4019 return X.getOperand(0); 4020 return SDValue(); 4021 }; 4022 4023 // Peek through a rotated value compared against 0 or -1: 4024 // (rot X, Y) == 0/-1 --> X == 0/-1 4025 // (rot X, Y) != 0/-1 --> X != 0/-1 4026 if (SDValue R = getRotateSource(N0)) 4027 return DAG.getSetCC(dl, VT, R, N1, Cond); 4028 4029 // Peek through an 'or' of a rotated value compared against 0: 4030 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 4031 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 4032 // 4033 // TODO: Add the 'and' with -1 sibling. 4034 // TODO: Recurse through a series of 'or' ops to find the rotate. 4035 EVT OpVT = N0.getValueType(); 4036 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 4037 if (SDValue R = getRotateSource(N0.getOperand(0))) { 4038 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 4039 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4040 } 4041 if (SDValue R = getRotateSource(N0.getOperand(1))) { 4042 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 4043 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4044 } 4045 } 4046 4047 return SDValue(); 4048 } 4049 4050 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 4051 ISD::CondCode Cond, const SDLoc &dl, 4052 SelectionDAG &DAG) { 4053 // If we are testing for all-bits-clear, we might be able to do that with 4054 // less shifting since bit-order does not matter. 4055 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4056 return SDValue(); 4057 4058 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4059 if (!C1 || !C1->isZero()) 4060 return SDValue(); 4061 4062 if (!N0.hasOneUse() || 4063 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4064 return SDValue(); 4065 4066 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4067 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4068 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4069 return SDValue(); 4070 4071 // Canonicalize fshr as fshl to reduce pattern-matching. 4072 unsigned ShAmt = ShAmtC->getZExtValue(); 4073 if (N0.getOpcode() == ISD::FSHR) 4074 ShAmt = BitWidth - ShAmt; 4075 4076 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4077 SDValue X, Y; 4078 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4079 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4080 return false; 4081 if (Or.getOperand(0) == Other) { 4082 X = Or.getOperand(0); 4083 Y = Or.getOperand(1); 4084 return true; 4085 } 4086 if (Or.getOperand(1) == Other) { 4087 X = Or.getOperand(1); 4088 Y = Or.getOperand(0); 4089 return true; 4090 } 4091 return false; 4092 }; 4093 4094 EVT OpVT = N0.getValueType(); 4095 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4096 SDValue F0 = N0.getOperand(0); 4097 SDValue F1 = N0.getOperand(1); 4098 if (matchOr(F0, F1)) { 4099 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4100 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4101 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4102 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4103 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4104 } 4105 if (matchOr(F1, F0)) { 4106 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4107 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4108 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4109 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4110 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4111 } 4112 4113 return SDValue(); 4114 } 4115 4116 /// Try to simplify a setcc built with the specified operands and cc. If it is 4117 /// unable to simplify it, return a null SDValue. 4118 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4119 ISD::CondCode Cond, bool foldBooleans, 4120 DAGCombinerInfo &DCI, 4121 const SDLoc &dl) const { 4122 SelectionDAG &DAG = DCI.DAG; 4123 const DataLayout &Layout = DAG.getDataLayout(); 4124 EVT OpVT = N0.getValueType(); 4125 4126 // Constant fold or commute setcc. 4127 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4128 return Fold; 4129 4130 bool N0ConstOrSplat = 4131 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4132 bool N1ConstOrSplat = 4133 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4134 4135 // Ensure that the constant occurs on the RHS and fold constant comparisons. 4136 // TODO: Handle non-splat vector constants. All undef causes trouble. 4137 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4138 // infinite loop here when we encounter one. 4139 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4140 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4141 (DCI.isBeforeLegalizeOps() || 4142 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4143 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4144 4145 // If we have a subtract with the same 2 non-constant operands as this setcc 4146 // -- but in reverse order -- then try to commute the operands of this setcc 4147 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4148 // instruction on some targets. 4149 if (!N0ConstOrSplat && !N1ConstOrSplat && 4150 (DCI.isBeforeLegalizeOps() || 4151 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4152 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4153 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4154 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4155 4156 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4157 return V; 4158 4159 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4160 return V; 4161 4162 if (auto *N1C = isConstOrConstSplat(N1)) { 4163 const APInt &C1 = N1C->getAPIntValue(); 4164 4165 // Optimize some CTPOP cases. 4166 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4167 return V; 4168 4169 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4170 // equality comparison, then we're just comparing whether X itself is 4171 // zero. 4172 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4173 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4174 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4175 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4176 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4177 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4178 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4179 // (srl (ctlz x), 5) == 0 -> X != 0 4180 // (srl (ctlz x), 5) != 1 -> X != 0 4181 Cond = ISD::SETNE; 4182 } else { 4183 // (srl (ctlz x), 5) != 0 -> X == 0 4184 // (srl (ctlz x), 5) == 1 -> X == 0 4185 Cond = ISD::SETEQ; 4186 } 4187 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4188 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4189 Cond); 4190 } 4191 } 4192 } 4193 } 4194 4195 // FIXME: Support vectors. 4196 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4197 const APInt &C1 = N1C->getAPIntValue(); 4198 4199 // (zext x) == C --> x == (trunc C) 4200 // (sext x) == C --> x == (trunc C) 4201 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4202 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4203 unsigned MinBits = N0.getValueSizeInBits(); 4204 SDValue PreExt; 4205 bool Signed = false; 4206 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4207 // ZExt 4208 MinBits = N0->getOperand(0).getValueSizeInBits(); 4209 PreExt = N0->getOperand(0); 4210 } else if (N0->getOpcode() == ISD::AND) { 4211 // DAGCombine turns costly ZExts into ANDs 4212 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4213 if ((C->getAPIntValue()+1).isPowerOf2()) { 4214 MinBits = C->getAPIntValue().countTrailingOnes(); 4215 PreExt = N0->getOperand(0); 4216 } 4217 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4218 // SExt 4219 MinBits = N0->getOperand(0).getValueSizeInBits(); 4220 PreExt = N0->getOperand(0); 4221 Signed = true; 4222 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4223 // ZEXTLOAD / SEXTLOAD 4224 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4225 MinBits = LN0->getMemoryVT().getSizeInBits(); 4226 PreExt = N0; 4227 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4228 Signed = true; 4229 MinBits = LN0->getMemoryVT().getSizeInBits(); 4230 PreExt = N0; 4231 } 4232 } 4233 4234 // Figure out how many bits we need to preserve this constant. 4235 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4236 4237 // Make sure we're not losing bits from the constant. 4238 if (MinBits > 0 && 4239 MinBits < C1.getBitWidth() && 4240 MinBits >= ReqdBits) { 4241 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4242 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4243 // Will get folded away. 4244 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4245 if (MinBits == 1 && C1 == 1) 4246 // Invert the condition. 4247 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4248 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4249 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4250 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4251 } 4252 4253 // If truncating the setcc operands is not desirable, we can still 4254 // simplify the expression in some cases: 4255 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4256 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4257 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4258 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4259 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4260 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4261 SDValue TopSetCC = N0->getOperand(0); 4262 unsigned N0Opc = N0->getOpcode(); 4263 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4264 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4265 TopSetCC.getOpcode() == ISD::SETCC && 4266 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4267 (isConstFalseVal(N1) || 4268 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4269 4270 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4271 (!N1C->isZero() && Cond == ISD::SETNE); 4272 4273 if (!Inverse) 4274 return TopSetCC; 4275 4276 ISD::CondCode InvCond = ISD::getSetCCInverse( 4277 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4278 TopSetCC.getOperand(0).getValueType()); 4279 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4280 TopSetCC.getOperand(1), 4281 InvCond); 4282 } 4283 } 4284 } 4285 4286 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4287 // equality or unsigned, and all 1 bits of the const are in the same 4288 // partial word, see if we can shorten the load. 4289 if (DCI.isBeforeLegalize() && 4290 !ISD::isSignedIntSetCC(Cond) && 4291 N0.getOpcode() == ISD::AND && C1 == 0 && 4292 N0.getNode()->hasOneUse() && 4293 isa<LoadSDNode>(N0.getOperand(0)) && 4294 N0.getOperand(0).getNode()->hasOneUse() && 4295 isa<ConstantSDNode>(N0.getOperand(1))) { 4296 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4297 APInt bestMask; 4298 unsigned bestWidth = 0, bestOffset = 0; 4299 if (Lod->isSimple() && Lod->isUnindexed()) { 4300 unsigned origWidth = N0.getValueSizeInBits(); 4301 unsigned maskWidth = origWidth; 4302 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4303 // 8 bits, but have to be careful... 4304 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4305 origWidth = Lod->getMemoryVT().getSizeInBits(); 4306 const APInt &Mask = N0.getConstantOperandAPInt(1); 4307 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4308 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4309 for (unsigned offset=0; offset<origWidth/width; offset++) { 4310 if (Mask.isSubsetOf(newMask)) { 4311 if (Layout.isLittleEndian()) 4312 bestOffset = (uint64_t)offset * (width/8); 4313 else 4314 bestOffset = (origWidth/width - offset - 1) * (width/8); 4315 bestMask = Mask.lshr(offset * (width/8) * 8); 4316 bestWidth = width; 4317 break; 4318 } 4319 newMask <<= width; 4320 } 4321 } 4322 } 4323 if (bestWidth) { 4324 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4325 if (newVT.isRound() && 4326 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4327 SDValue Ptr = Lod->getBasePtr(); 4328 if (bestOffset != 0) 4329 Ptr = 4330 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4331 SDValue NewLoad = 4332 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4333 Lod->getPointerInfo().getWithOffset(bestOffset), 4334 Lod->getOriginalAlign()); 4335 return DAG.getSetCC(dl, VT, 4336 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4337 DAG.getConstant(bestMask.trunc(bestWidth), 4338 dl, newVT)), 4339 DAG.getConstant(0LL, dl, newVT), Cond); 4340 } 4341 } 4342 } 4343 4344 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4345 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4346 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4347 4348 // If the comparison constant has bits in the upper part, the 4349 // zero-extended value could never match. 4350 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4351 C1.getBitWidth() - InSize))) { 4352 switch (Cond) { 4353 case ISD::SETUGT: 4354 case ISD::SETUGE: 4355 case ISD::SETEQ: 4356 return DAG.getConstant(0, dl, VT); 4357 case ISD::SETULT: 4358 case ISD::SETULE: 4359 case ISD::SETNE: 4360 return DAG.getConstant(1, dl, VT); 4361 case ISD::SETGT: 4362 case ISD::SETGE: 4363 // True if the sign bit of C1 is set. 4364 return DAG.getConstant(C1.isNegative(), dl, VT); 4365 case ISD::SETLT: 4366 case ISD::SETLE: 4367 // True if the sign bit of C1 isn't set. 4368 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4369 default: 4370 break; 4371 } 4372 } 4373 4374 // Otherwise, we can perform the comparison with the low bits. 4375 switch (Cond) { 4376 case ISD::SETEQ: 4377 case ISD::SETNE: 4378 case ISD::SETUGT: 4379 case ISD::SETUGE: 4380 case ISD::SETULT: 4381 case ISD::SETULE: { 4382 EVT newVT = N0.getOperand(0).getValueType(); 4383 if (DCI.isBeforeLegalizeOps() || 4384 (isOperationLegal(ISD::SETCC, newVT) && 4385 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4386 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4387 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4388 4389 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4390 NewConst, Cond); 4391 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4392 } 4393 break; 4394 } 4395 default: 4396 break; // todo, be more careful with signed comparisons 4397 } 4398 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4399 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4400 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4401 OpVT)) { 4402 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4403 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4404 EVT ExtDstTy = N0.getValueType(); 4405 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4406 4407 // If the constant doesn't fit into the number of bits for the source of 4408 // the sign extension, it is impossible for both sides to be equal. 4409 if (C1.getMinSignedBits() > ExtSrcTyBits) 4410 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4411 4412 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4413 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4414 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4415 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4416 DAG.getConstant(Imm, dl, ExtDstTy)); 4417 if (!DCI.isCalledByLegalizer()) 4418 DCI.AddToWorklist(ZextOp.getNode()); 4419 // Otherwise, make this a use of a zext. 4420 return DAG.getSetCC(dl, VT, ZextOp, 4421 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4422 } else if ((N1C->isZero() || N1C->isOne()) && 4423 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4424 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4425 if (N0.getOpcode() == ISD::SETCC && 4426 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4427 (N0.getValueType() == MVT::i1 || 4428 getBooleanContents(N0.getOperand(0).getValueType()) == 4429 ZeroOrOneBooleanContent)) { 4430 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4431 if (TrueWhenTrue) 4432 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4433 // Invert the condition. 4434 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4435 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4436 if (DCI.isBeforeLegalizeOps() || 4437 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4438 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4439 } 4440 4441 if ((N0.getOpcode() == ISD::XOR || 4442 (N0.getOpcode() == ISD::AND && 4443 N0.getOperand(0).getOpcode() == ISD::XOR && 4444 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4445 isOneConstant(N0.getOperand(1))) { 4446 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4447 // can only do this if the top bits are known zero. 4448 unsigned BitWidth = N0.getValueSizeInBits(); 4449 if (DAG.MaskedValueIsZero(N0, 4450 APInt::getHighBitsSet(BitWidth, 4451 BitWidth-1))) { 4452 // Okay, get the un-inverted input value. 4453 SDValue Val; 4454 if (N0.getOpcode() == ISD::XOR) { 4455 Val = N0.getOperand(0); 4456 } else { 4457 assert(N0.getOpcode() == ISD::AND && 4458 N0.getOperand(0).getOpcode() == ISD::XOR); 4459 // ((X^1)&1)^1 -> X & 1 4460 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4461 N0.getOperand(0).getOperand(0), 4462 N0.getOperand(1)); 4463 } 4464 4465 return DAG.getSetCC(dl, VT, Val, N1, 4466 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4467 } 4468 } else if (N1C->isOne()) { 4469 SDValue Op0 = N0; 4470 if (Op0.getOpcode() == ISD::TRUNCATE) 4471 Op0 = Op0.getOperand(0); 4472 4473 if ((Op0.getOpcode() == ISD::XOR) && 4474 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4475 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4476 SDValue XorLHS = Op0.getOperand(0); 4477 SDValue XorRHS = Op0.getOperand(1); 4478 // Ensure that the input setccs return an i1 type or 0/1 value. 4479 if (Op0.getValueType() == MVT::i1 || 4480 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4481 ZeroOrOneBooleanContent && 4482 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4483 ZeroOrOneBooleanContent)) { 4484 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4485 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4486 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4487 } 4488 } 4489 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4490 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4491 if (Op0.getValueType().bitsGT(VT)) 4492 Op0 = DAG.getNode(ISD::AND, dl, VT, 4493 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4494 DAG.getConstant(1, dl, VT)); 4495 else if (Op0.getValueType().bitsLT(VT)) 4496 Op0 = DAG.getNode(ISD::AND, dl, VT, 4497 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4498 DAG.getConstant(1, dl, VT)); 4499 4500 return DAG.getSetCC(dl, VT, Op0, 4501 DAG.getConstant(0, dl, Op0.getValueType()), 4502 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4503 } 4504 if (Op0.getOpcode() == ISD::AssertZext && 4505 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4506 return DAG.getSetCC(dl, VT, Op0, 4507 DAG.getConstant(0, dl, Op0.getValueType()), 4508 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4509 } 4510 } 4511 4512 // Given: 4513 // icmp eq/ne (urem %x, %y), 0 4514 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4515 // icmp eq/ne %x, 0 4516 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4517 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4518 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4519 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4520 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4521 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4522 } 4523 4524 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4525 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4526 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4527 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4528 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4529 N1C && N1C->isAllOnes()) { 4530 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4531 DAG.getConstant(0, dl, OpVT), 4532 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4533 } 4534 4535 if (SDValue V = 4536 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4537 return V; 4538 } 4539 4540 // These simplifications apply to splat vectors as well. 4541 // TODO: Handle more splat vector cases. 4542 if (auto *N1C = isConstOrConstSplat(N1)) { 4543 const APInt &C1 = N1C->getAPIntValue(); 4544 4545 APInt MinVal, MaxVal; 4546 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4547 if (ISD::isSignedIntSetCC(Cond)) { 4548 MinVal = APInt::getSignedMinValue(OperandBitSize); 4549 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4550 } else { 4551 MinVal = APInt::getMinValue(OperandBitSize); 4552 MaxVal = APInt::getMaxValue(OperandBitSize); 4553 } 4554 4555 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4556 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4557 // X >= MIN --> true 4558 if (C1 == MinVal) 4559 return DAG.getBoolConstant(true, dl, VT, OpVT); 4560 4561 if (!VT.isVector()) { // TODO: Support this for vectors. 4562 // X >= C0 --> X > (C0 - 1) 4563 APInt C = C1 - 1; 4564 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4565 if ((DCI.isBeforeLegalizeOps() || 4566 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4567 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4568 isLegalICmpImmediate(C.getSExtValue())))) { 4569 return DAG.getSetCC(dl, VT, N0, 4570 DAG.getConstant(C, dl, N1.getValueType()), 4571 NewCC); 4572 } 4573 } 4574 } 4575 4576 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4577 // X <= MAX --> true 4578 if (C1 == MaxVal) 4579 return DAG.getBoolConstant(true, dl, VT, OpVT); 4580 4581 // X <= C0 --> X < (C0 + 1) 4582 if (!VT.isVector()) { // TODO: Support this for vectors. 4583 APInt C = C1 + 1; 4584 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4585 if ((DCI.isBeforeLegalizeOps() || 4586 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4587 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4588 isLegalICmpImmediate(C.getSExtValue())))) { 4589 return DAG.getSetCC(dl, VT, N0, 4590 DAG.getConstant(C, dl, N1.getValueType()), 4591 NewCC); 4592 } 4593 } 4594 } 4595 4596 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4597 if (C1 == MinVal) 4598 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4599 4600 // TODO: Support this for vectors after legalize ops. 4601 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4602 // Canonicalize setlt X, Max --> setne X, Max 4603 if (C1 == MaxVal) 4604 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4605 4606 // If we have setult X, 1, turn it into seteq X, 0 4607 if (C1 == MinVal+1) 4608 return DAG.getSetCC(dl, VT, N0, 4609 DAG.getConstant(MinVal, dl, N0.getValueType()), 4610 ISD::SETEQ); 4611 } 4612 } 4613 4614 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4615 if (C1 == MaxVal) 4616 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4617 4618 // TODO: Support this for vectors after legalize ops. 4619 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4620 // Canonicalize setgt X, Min --> setne X, Min 4621 if (C1 == MinVal) 4622 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4623 4624 // If we have setugt X, Max-1, turn it into seteq X, Max 4625 if (C1 == MaxVal-1) 4626 return DAG.getSetCC(dl, VT, N0, 4627 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4628 ISD::SETEQ); 4629 } 4630 } 4631 4632 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4633 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4634 if (C1.isZero()) 4635 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4636 VT, N0, N1, Cond, DCI, dl)) 4637 return CC; 4638 4639 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4640 // For example, when high 32-bits of i64 X are known clear: 4641 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4642 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4643 bool CmpZero = N1C->getAPIntValue().isZero(); 4644 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4645 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4646 // Match or(lo,shl(hi,bw/2)) pattern. 4647 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4648 unsigned EltBits = V.getScalarValueSizeInBits(); 4649 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4650 return false; 4651 SDValue LHS = V.getOperand(0); 4652 SDValue RHS = V.getOperand(1); 4653 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4654 // Unshifted element must have zero upperbits. 4655 if (RHS.getOpcode() == ISD::SHL && 4656 isa<ConstantSDNode>(RHS.getOperand(1)) && 4657 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4658 DAG.MaskedValueIsZero(LHS, HiBits)) { 4659 Lo = LHS; 4660 Hi = RHS.getOperand(0); 4661 return true; 4662 } 4663 if (LHS.getOpcode() == ISD::SHL && 4664 isa<ConstantSDNode>(LHS.getOperand(1)) && 4665 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4666 DAG.MaskedValueIsZero(RHS, HiBits)) { 4667 Lo = RHS; 4668 Hi = LHS.getOperand(0); 4669 return true; 4670 } 4671 return false; 4672 }; 4673 4674 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4675 unsigned EltBits = N0.getScalarValueSizeInBits(); 4676 unsigned HalfBits = EltBits / 2; 4677 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4678 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4679 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4680 SDValue NewN0 = 4681 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4682 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4683 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4684 }; 4685 4686 SDValue Lo, Hi; 4687 if (IsConcat(N0, Lo, Hi)) 4688 return MergeConcat(Lo, Hi); 4689 4690 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4691 SDValue Lo0, Lo1, Hi0, Hi1; 4692 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4693 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4694 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4695 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4696 } 4697 } 4698 } 4699 } 4700 4701 // If we have "setcc X, C0", check to see if we can shrink the immediate 4702 // by changing cc. 4703 // TODO: Support this for vectors after legalize ops. 4704 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4705 // SETUGT X, SINTMAX -> SETLT X, 0 4706 // SETUGE X, SINTMIN -> SETLT X, 0 4707 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4708 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4709 return DAG.getSetCC(dl, VT, N0, 4710 DAG.getConstant(0, dl, N1.getValueType()), 4711 ISD::SETLT); 4712 4713 // SETULT X, SINTMIN -> SETGT X, -1 4714 // SETULE X, SINTMAX -> SETGT X, -1 4715 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4716 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4717 return DAG.getSetCC(dl, VT, N0, 4718 DAG.getAllOnesConstant(dl, N1.getValueType()), 4719 ISD::SETGT); 4720 } 4721 } 4722 4723 // Back to non-vector simplifications. 4724 // TODO: Can we do these for vector splats? 4725 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4726 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4727 const APInt &C1 = N1C->getAPIntValue(); 4728 EVT ShValTy = N0.getValueType(); 4729 4730 // Fold bit comparisons when we can. This will result in an 4731 // incorrect value when boolean false is negative one, unless 4732 // the bitsize is 1 in which case the false value is the same 4733 // in practice regardless of the representation. 4734 if ((VT.getSizeInBits() == 1 || 4735 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4736 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4737 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4738 N0.getOpcode() == ISD::AND) { 4739 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4740 EVT ShiftTy = 4741 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4742 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4743 // Perform the xform if the AND RHS is a single bit. 4744 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4745 if (AndRHS->getAPIntValue().isPowerOf2() && 4746 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4747 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4748 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4749 DAG.getConstant(ShCt, dl, ShiftTy))); 4750 } 4751 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4752 // (X & 8) == 8 --> (X & 8) >> 3 4753 // Perform the xform if C1 is a single bit. 4754 unsigned ShCt = C1.logBase2(); 4755 if (C1.isPowerOf2() && 4756 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4757 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4758 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4759 DAG.getConstant(ShCt, dl, ShiftTy))); 4760 } 4761 } 4762 } 4763 } 4764 4765 if (C1.getMinSignedBits() <= 64 && 4766 !isLegalICmpImmediate(C1.getSExtValue())) { 4767 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4768 // (X & -256) == 256 -> (X >> 8) == 1 4769 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4770 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4771 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4772 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4773 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4774 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4775 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4776 SDValue Shift = 4777 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4778 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4779 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4780 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4781 } 4782 } 4783 } 4784 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4785 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4786 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4787 // X < 0x100000000 -> (X >> 32) < 1 4788 // X >= 0x100000000 -> (X >> 32) >= 1 4789 // X <= 0x0ffffffff -> (X >> 32) < 1 4790 // X > 0x0ffffffff -> (X >> 32) >= 1 4791 unsigned ShiftBits; 4792 APInt NewC = C1; 4793 ISD::CondCode NewCond = Cond; 4794 if (AdjOne) { 4795 ShiftBits = C1.countTrailingOnes(); 4796 NewC = NewC + 1; 4797 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4798 } else { 4799 ShiftBits = C1.countTrailingZeros(); 4800 } 4801 NewC.lshrInPlace(ShiftBits); 4802 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4803 isLegalICmpImmediate(NewC.getSExtValue()) && 4804 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4805 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4806 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4807 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4808 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4809 } 4810 } 4811 } 4812 } 4813 4814 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4815 auto *CFP = cast<ConstantFPSDNode>(N1); 4816 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4817 4818 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4819 // constant if knowing that the operand is non-nan is enough. We prefer to 4820 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4821 // materialize 0.0. 4822 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4823 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4824 4825 // setcc (fneg x), C -> setcc swap(pred) x, -C 4826 if (N0.getOpcode() == ISD::FNEG) { 4827 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4828 if (DCI.isBeforeLegalizeOps() || 4829 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4830 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4831 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4832 } 4833 } 4834 4835 // If the condition is not legal, see if we can find an equivalent one 4836 // which is legal. 4837 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4838 // If the comparison was an awkward floating-point == or != and one of 4839 // the comparison operands is infinity or negative infinity, convert the 4840 // condition to a less-awkward <= or >=. 4841 if (CFP->getValueAPF().isInfinity()) { 4842 bool IsNegInf = CFP->getValueAPF().isNegative(); 4843 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4844 switch (Cond) { 4845 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4846 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4847 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4848 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4849 default: break; 4850 } 4851 if (NewCond != ISD::SETCC_INVALID && 4852 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4853 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4854 } 4855 } 4856 } 4857 4858 if (N0 == N1) { 4859 // The sext(setcc()) => setcc() optimization relies on the appropriate 4860 // constant being emitted. 4861 assert(!N0.getValueType().isInteger() && 4862 "Integer types should be handled by FoldSetCC"); 4863 4864 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4865 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4866 if (UOF == 2) // FP operators that are undefined on NaNs. 4867 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4868 if (UOF == unsigned(EqTrue)) 4869 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4870 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4871 // if it is not already. 4872 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4873 if (NewCond != Cond && 4874 (DCI.isBeforeLegalizeOps() || 4875 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4876 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4877 } 4878 4879 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4880 N0.getValueType().isInteger()) { 4881 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4882 N0.getOpcode() == ISD::XOR) { 4883 // Simplify (X+Y) == (X+Z) --> Y == Z 4884 if (N0.getOpcode() == N1.getOpcode()) { 4885 if (N0.getOperand(0) == N1.getOperand(0)) 4886 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4887 if (N0.getOperand(1) == N1.getOperand(1)) 4888 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4889 if (isCommutativeBinOp(N0.getOpcode())) { 4890 // If X op Y == Y op X, try other combinations. 4891 if (N0.getOperand(0) == N1.getOperand(1)) 4892 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4893 Cond); 4894 if (N0.getOperand(1) == N1.getOperand(0)) 4895 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4896 Cond); 4897 } 4898 } 4899 4900 // If RHS is a legal immediate value for a compare instruction, we need 4901 // to be careful about increasing register pressure needlessly. 4902 bool LegalRHSImm = false; 4903 4904 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4905 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4906 // Turn (X+C1) == C2 --> X == C2-C1 4907 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4908 return DAG.getSetCC( 4909 dl, VT, N0.getOperand(0), 4910 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4911 dl, N0.getValueType()), 4912 Cond); 4913 4914 // Turn (X^C1) == C2 --> X == C1^C2 4915 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4916 return DAG.getSetCC( 4917 dl, VT, N0.getOperand(0), 4918 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4919 dl, N0.getValueType()), 4920 Cond); 4921 } 4922 4923 // Turn (C1-X) == C2 --> X == C1-C2 4924 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4925 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4926 return DAG.getSetCC( 4927 dl, VT, N0.getOperand(1), 4928 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4929 dl, N0.getValueType()), 4930 Cond); 4931 4932 // Could RHSC fold directly into a compare? 4933 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4934 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4935 } 4936 4937 // (X+Y) == X --> Y == 0 and similar folds. 4938 // Don't do this if X is an immediate that can fold into a cmp 4939 // instruction and X+Y has other uses. It could be an induction variable 4940 // chain, and the transform would increase register pressure. 4941 if (!LegalRHSImm || N0.hasOneUse()) 4942 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4943 return V; 4944 } 4945 4946 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4947 N1.getOpcode() == ISD::XOR) 4948 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4949 return V; 4950 4951 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4952 return V; 4953 } 4954 4955 // Fold remainder of division by a constant. 4956 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4957 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4958 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4959 4960 // When division is cheap or optimizing for minimum size, 4961 // fall through to DIVREM creation by skipping this fold. 4962 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4963 if (N0.getOpcode() == ISD::UREM) { 4964 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4965 return Folded; 4966 } else if (N0.getOpcode() == ISD::SREM) { 4967 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4968 return Folded; 4969 } 4970 } 4971 } 4972 4973 // Fold away ALL boolean setcc's. 4974 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4975 SDValue Temp; 4976 switch (Cond) { 4977 default: llvm_unreachable("Unknown integer setcc!"); 4978 case ISD::SETEQ: // X == Y -> ~(X^Y) 4979 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4980 N0 = DAG.getNOT(dl, Temp, OpVT); 4981 if (!DCI.isCalledByLegalizer()) 4982 DCI.AddToWorklist(Temp.getNode()); 4983 break; 4984 case ISD::SETNE: // X != Y --> (X^Y) 4985 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4986 break; 4987 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4988 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4989 Temp = DAG.getNOT(dl, N0, OpVT); 4990 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4991 if (!DCI.isCalledByLegalizer()) 4992 DCI.AddToWorklist(Temp.getNode()); 4993 break; 4994 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4995 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4996 Temp = DAG.getNOT(dl, N1, OpVT); 4997 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4998 if (!DCI.isCalledByLegalizer()) 4999 DCI.AddToWorklist(Temp.getNode()); 5000 break; 5001 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 5002 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 5003 Temp = DAG.getNOT(dl, N0, OpVT); 5004 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 5005 if (!DCI.isCalledByLegalizer()) 5006 DCI.AddToWorklist(Temp.getNode()); 5007 break; 5008 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 5009 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 5010 Temp = DAG.getNOT(dl, N1, OpVT); 5011 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 5012 break; 5013 } 5014 if (VT.getScalarType() != MVT::i1) { 5015 if (!DCI.isCalledByLegalizer()) 5016 DCI.AddToWorklist(N0.getNode()); 5017 // FIXME: If running after legalize, we probably can't do this. 5018 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 5019 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 5020 } 5021 return N0; 5022 } 5023 5024 // Could not fold it. 5025 return SDValue(); 5026 } 5027 5028 /// Returns true (and the GlobalValue and the offset) if the node is a 5029 /// GlobalAddress + offset. 5030 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 5031 int64_t &Offset) const { 5032 5033 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 5034 5035 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 5036 GA = GASD->getGlobal(); 5037 Offset += GASD->getOffset(); 5038 return true; 5039 } 5040 5041 if (N->getOpcode() == ISD::ADD) { 5042 SDValue N1 = N->getOperand(0); 5043 SDValue N2 = N->getOperand(1); 5044 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 5045 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 5046 Offset += V->getSExtValue(); 5047 return true; 5048 } 5049 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 5050 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 5051 Offset += V->getSExtValue(); 5052 return true; 5053 } 5054 } 5055 } 5056 5057 return false; 5058 } 5059 5060 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5061 DAGCombinerInfo &DCI) const { 5062 // Default implementation: no optimization. 5063 return SDValue(); 5064 } 5065 5066 //===----------------------------------------------------------------------===// 5067 // Inline Assembler Implementation Methods 5068 //===----------------------------------------------------------------------===// 5069 5070 TargetLowering::ConstraintType 5071 TargetLowering::getConstraintType(StringRef Constraint) const { 5072 unsigned S = Constraint.size(); 5073 5074 if (S == 1) { 5075 switch (Constraint[0]) { 5076 default: break; 5077 case 'r': 5078 return C_RegisterClass; 5079 case 'm': // memory 5080 case 'o': // offsetable 5081 case 'V': // not offsetable 5082 return C_Memory; 5083 case 'p': // Address. 5084 return C_Address; 5085 case 'n': // Simple Integer 5086 case 'E': // Floating Point Constant 5087 case 'F': // Floating Point Constant 5088 return C_Immediate; 5089 case 'i': // Simple Integer or Relocatable Constant 5090 case 's': // Relocatable Constant 5091 case 'X': // Allow ANY value. 5092 case 'I': // Target registers. 5093 case 'J': 5094 case 'K': 5095 case 'L': 5096 case 'M': 5097 case 'N': 5098 case 'O': 5099 case 'P': 5100 case '<': 5101 case '>': 5102 return C_Other; 5103 } 5104 } 5105 5106 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5107 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5108 return C_Memory; 5109 return C_Register; 5110 } 5111 return C_Unknown; 5112 } 5113 5114 /// Try to replace an X constraint, which matches anything, with another that 5115 /// has more specific requirements based on the type of the corresponding 5116 /// operand. 5117 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5118 if (ConstraintVT.isInteger()) 5119 return "r"; 5120 if (ConstraintVT.isFloatingPoint()) 5121 return "f"; // works for many targets 5122 return nullptr; 5123 } 5124 5125 SDValue TargetLowering::LowerAsmOutputForConstraint( 5126 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 5127 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5128 return SDValue(); 5129 } 5130 5131 /// Lower the specified operand into the Ops vector. 5132 /// If it is invalid, don't add anything to Ops. 5133 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5134 std::string &Constraint, 5135 std::vector<SDValue> &Ops, 5136 SelectionDAG &DAG) const { 5137 5138 if (Constraint.length() > 1) return; 5139 5140 char ConstraintLetter = Constraint[0]; 5141 switch (ConstraintLetter) { 5142 default: break; 5143 case 'X': // Allows any operand 5144 case 'i': // Simple Integer or Relocatable Constant 5145 case 'n': // Simple Integer 5146 case 's': { // Relocatable Constant 5147 5148 ConstantSDNode *C; 5149 uint64_t Offset = 0; 5150 5151 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5152 // etc., since getelementpointer is variadic. We can't use 5153 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5154 // while in this case the GA may be furthest from the root node which is 5155 // likely an ISD::ADD. 5156 while (true) { 5157 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5158 // gcc prints these as sign extended. Sign extend value to 64 bits 5159 // now; without this it would get ZExt'd later in 5160 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5161 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5162 BooleanContent BCont = getBooleanContents(MVT::i64); 5163 ISD::NodeType ExtOpc = 5164 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5165 int64_t ExtVal = 5166 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5167 Ops.push_back( 5168 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5169 return; 5170 } 5171 if (ConstraintLetter != 'n') { 5172 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5173 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5174 GA->getValueType(0), 5175 Offset + GA->getOffset())); 5176 return; 5177 } 5178 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5179 Ops.push_back(DAG.getTargetBlockAddress( 5180 BA->getBlockAddress(), BA->getValueType(0), 5181 Offset + BA->getOffset(), BA->getTargetFlags())); 5182 return; 5183 } 5184 if (isa<BasicBlockSDNode>(Op)) { 5185 Ops.push_back(Op); 5186 return; 5187 } 5188 } 5189 const unsigned OpCode = Op.getOpcode(); 5190 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5191 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5192 Op = Op.getOperand(1); 5193 // Subtraction is not commutative. 5194 else if (OpCode == ISD::ADD && 5195 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5196 Op = Op.getOperand(0); 5197 else 5198 return; 5199 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5200 continue; 5201 } 5202 return; 5203 } 5204 break; 5205 } 5206 } 5207 } 5208 5209 std::pair<unsigned, const TargetRegisterClass *> 5210 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5211 StringRef Constraint, 5212 MVT VT) const { 5213 if (Constraint.empty() || Constraint[0] != '{') 5214 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5215 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5216 5217 // Remove the braces from around the name. 5218 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5219 5220 std::pair<unsigned, const TargetRegisterClass *> R = 5221 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5222 5223 // Figure out which register class contains this reg. 5224 for (const TargetRegisterClass *RC : RI->regclasses()) { 5225 // If none of the value types for this register class are valid, we 5226 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5227 if (!isLegalRC(*RI, *RC)) 5228 continue; 5229 5230 for (const MCPhysReg &PR : *RC) { 5231 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5232 std::pair<unsigned, const TargetRegisterClass *> S = 5233 std::make_pair(PR, RC); 5234 5235 // If this register class has the requested value type, return it, 5236 // otherwise keep searching and return the first class found 5237 // if no other is found which explicitly has the requested type. 5238 if (RI->isTypeLegalForClass(*RC, VT)) 5239 return S; 5240 if (!R.second) 5241 R = S; 5242 } 5243 } 5244 } 5245 5246 return R; 5247 } 5248 5249 //===----------------------------------------------------------------------===// 5250 // Constraint Selection. 5251 5252 /// Return true of this is an input operand that is a matching constraint like 5253 /// "4". 5254 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5255 assert(!ConstraintCode.empty() && "No known constraint!"); 5256 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5257 } 5258 5259 /// If this is an input matching constraint, this method returns the output 5260 /// operand it matches. 5261 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5262 assert(!ConstraintCode.empty() && "No known constraint!"); 5263 return atoi(ConstraintCode.c_str()); 5264 } 5265 5266 /// Split up the constraint string from the inline assembly value into the 5267 /// specific constraints and their prefixes, and also tie in the associated 5268 /// operand values. 5269 /// If this returns an empty vector, and if the constraint string itself 5270 /// isn't empty, there was an error parsing. 5271 TargetLowering::AsmOperandInfoVector 5272 TargetLowering::ParseConstraints(const DataLayout &DL, 5273 const TargetRegisterInfo *TRI, 5274 const CallBase &Call) const { 5275 /// Information about all of the constraints. 5276 AsmOperandInfoVector ConstraintOperands; 5277 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5278 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5279 5280 // Do a prepass over the constraints, canonicalizing them, and building up the 5281 // ConstraintOperands list. 5282 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5283 unsigned ResNo = 0; // ResNo - The result number of the next output. 5284 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number. 5285 5286 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5287 ConstraintOperands.emplace_back(std::move(CI)); 5288 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5289 5290 // Update multiple alternative constraint count. 5291 if (OpInfo.multipleAlternatives.size() > maCount) 5292 maCount = OpInfo.multipleAlternatives.size(); 5293 5294 OpInfo.ConstraintVT = MVT::Other; 5295 5296 // Compute the value type for each operand. 5297 switch (OpInfo.Type) { 5298 case InlineAsm::isOutput: 5299 // Indirect outputs just consume an argument. 5300 if (OpInfo.isIndirect) { 5301 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5302 break; 5303 } 5304 5305 // The return value of the call is this value. As such, there is no 5306 // corresponding argument. 5307 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5308 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5309 OpInfo.ConstraintVT = 5310 getSimpleValueType(DL, STy->getElementType(ResNo)); 5311 } else { 5312 assert(ResNo == 0 && "Asm only has one result!"); 5313 OpInfo.ConstraintVT = 5314 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5315 } 5316 ++ResNo; 5317 break; 5318 case InlineAsm::isInput: 5319 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5320 break; 5321 case InlineAsm::isLabel: 5322 OpInfo.CallOperandVal = 5323 cast<CallBrInst>(&Call)->getBlockAddressForIndirectDest(LabelNo); 5324 OpInfo.ConstraintVT = 5325 getAsmOperandValueType(DL, OpInfo.CallOperandVal->getType()) 5326 .getSimpleVT(); 5327 ++LabelNo; 5328 continue; 5329 case InlineAsm::isClobber: 5330 // Nothing to do. 5331 break; 5332 } 5333 5334 if (OpInfo.CallOperandVal) { 5335 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5336 if (OpInfo.isIndirect) { 5337 OpTy = Call.getParamElementType(ArgNo); 5338 assert(OpTy && "Indirect operand must have elementtype attribute"); 5339 } 5340 5341 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5342 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5343 if (STy->getNumElements() == 1) 5344 OpTy = STy->getElementType(0); 5345 5346 // If OpTy is not a single value, it may be a struct/union that we 5347 // can tile with integers. 5348 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5349 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5350 switch (BitSize) { 5351 default: break; 5352 case 1: 5353 case 8: 5354 case 16: 5355 case 32: 5356 case 64: 5357 case 128: 5358 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5359 break; 5360 } 5361 } 5362 5363 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5364 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5365 ArgNo++; 5366 } 5367 } 5368 5369 // If we have multiple alternative constraints, select the best alternative. 5370 if (!ConstraintOperands.empty()) { 5371 if (maCount) { 5372 unsigned bestMAIndex = 0; 5373 int bestWeight = -1; 5374 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5375 int weight = -1; 5376 unsigned maIndex; 5377 // Compute the sums of the weights for each alternative, keeping track 5378 // of the best (highest weight) one so far. 5379 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5380 int weightSum = 0; 5381 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5382 cIndex != eIndex; ++cIndex) { 5383 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5384 if (OpInfo.Type == InlineAsm::isClobber) 5385 continue; 5386 5387 // If this is an output operand with a matching input operand, 5388 // look up the matching input. If their types mismatch, e.g. one 5389 // is an integer, the other is floating point, or their sizes are 5390 // different, flag it as an maCantMatch. 5391 if (OpInfo.hasMatchingInput()) { 5392 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5393 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5394 if ((OpInfo.ConstraintVT.isInteger() != 5395 Input.ConstraintVT.isInteger()) || 5396 (OpInfo.ConstraintVT.getSizeInBits() != 5397 Input.ConstraintVT.getSizeInBits())) { 5398 weightSum = -1; // Can't match. 5399 break; 5400 } 5401 } 5402 } 5403 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5404 if (weight == -1) { 5405 weightSum = -1; 5406 break; 5407 } 5408 weightSum += weight; 5409 } 5410 // Update best. 5411 if (weightSum > bestWeight) { 5412 bestWeight = weightSum; 5413 bestMAIndex = maIndex; 5414 } 5415 } 5416 5417 // Now select chosen alternative in each constraint. 5418 for (AsmOperandInfo &cInfo : ConstraintOperands) 5419 if (cInfo.Type != InlineAsm::isClobber) 5420 cInfo.selectAlternative(bestMAIndex); 5421 } 5422 } 5423 5424 // Check and hook up tied operands, choose constraint code to use. 5425 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5426 cIndex != eIndex; ++cIndex) { 5427 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5428 5429 // If this is an output operand with a matching input operand, look up the 5430 // matching input. If their types mismatch, e.g. one is an integer, the 5431 // other is floating point, or their sizes are different, flag it as an 5432 // error. 5433 if (OpInfo.hasMatchingInput()) { 5434 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5435 5436 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5437 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5438 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5439 OpInfo.ConstraintVT); 5440 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5441 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5442 Input.ConstraintVT); 5443 if ((OpInfo.ConstraintVT.isInteger() != 5444 Input.ConstraintVT.isInteger()) || 5445 (MatchRC.second != InputRC.second)) { 5446 report_fatal_error("Unsupported asm: input constraint" 5447 " with a matching output constraint of" 5448 " incompatible type!"); 5449 } 5450 } 5451 } 5452 } 5453 5454 return ConstraintOperands; 5455 } 5456 5457 /// Return an integer indicating how general CT is. 5458 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5459 switch (CT) { 5460 case TargetLowering::C_Immediate: 5461 case TargetLowering::C_Other: 5462 case TargetLowering::C_Unknown: 5463 return 0; 5464 case TargetLowering::C_Register: 5465 return 1; 5466 case TargetLowering::C_RegisterClass: 5467 return 2; 5468 case TargetLowering::C_Memory: 5469 case TargetLowering::C_Address: 5470 return 3; 5471 } 5472 llvm_unreachable("Invalid constraint type"); 5473 } 5474 5475 /// Examine constraint type and operand type and determine a weight value. 5476 /// This object must already have been set up with the operand type 5477 /// and the current alternative constraint selected. 5478 TargetLowering::ConstraintWeight 5479 TargetLowering::getMultipleConstraintMatchWeight( 5480 AsmOperandInfo &info, int maIndex) const { 5481 InlineAsm::ConstraintCodeVector *rCodes; 5482 if (maIndex >= (int)info.multipleAlternatives.size()) 5483 rCodes = &info.Codes; 5484 else 5485 rCodes = &info.multipleAlternatives[maIndex].Codes; 5486 ConstraintWeight BestWeight = CW_Invalid; 5487 5488 // Loop over the options, keeping track of the most general one. 5489 for (const std::string &rCode : *rCodes) { 5490 ConstraintWeight weight = 5491 getSingleConstraintMatchWeight(info, rCode.c_str()); 5492 if (weight > BestWeight) 5493 BestWeight = weight; 5494 } 5495 5496 return BestWeight; 5497 } 5498 5499 /// Examine constraint type and operand type and determine a weight value. 5500 /// This object must already have been set up with the operand type 5501 /// and the current alternative constraint selected. 5502 TargetLowering::ConstraintWeight 5503 TargetLowering::getSingleConstraintMatchWeight( 5504 AsmOperandInfo &info, const char *constraint) const { 5505 ConstraintWeight weight = CW_Invalid; 5506 Value *CallOperandVal = info.CallOperandVal; 5507 // If we don't have a value, we can't do a match, 5508 // but allow it at the lowest weight. 5509 if (!CallOperandVal) 5510 return CW_Default; 5511 // Look at the constraint type. 5512 switch (*constraint) { 5513 case 'i': // immediate integer. 5514 case 'n': // immediate integer with a known value. 5515 if (isa<ConstantInt>(CallOperandVal)) 5516 weight = CW_Constant; 5517 break; 5518 case 's': // non-explicit intregal immediate. 5519 if (isa<GlobalValue>(CallOperandVal)) 5520 weight = CW_Constant; 5521 break; 5522 case 'E': // immediate float if host format. 5523 case 'F': // immediate float. 5524 if (isa<ConstantFP>(CallOperandVal)) 5525 weight = CW_Constant; 5526 break; 5527 case '<': // memory operand with autodecrement. 5528 case '>': // memory operand with autoincrement. 5529 case 'm': // memory operand. 5530 case 'o': // offsettable memory operand 5531 case 'V': // non-offsettable memory operand 5532 weight = CW_Memory; 5533 break; 5534 case 'r': // general register. 5535 case 'g': // general register, memory operand or immediate integer. 5536 // note: Clang converts "g" to "imr". 5537 if (CallOperandVal->getType()->isIntegerTy()) 5538 weight = CW_Register; 5539 break; 5540 case 'X': // any operand. 5541 default: 5542 weight = CW_Default; 5543 break; 5544 } 5545 return weight; 5546 } 5547 5548 /// If there are multiple different constraints that we could pick for this 5549 /// operand (e.g. "imr") try to pick the 'best' one. 5550 /// This is somewhat tricky: constraints fall into four classes: 5551 /// Other -> immediates and magic values 5552 /// Register -> one specific register 5553 /// RegisterClass -> a group of regs 5554 /// Memory -> memory 5555 /// Ideally, we would pick the most specific constraint possible: if we have 5556 /// something that fits into a register, we would pick it. The problem here 5557 /// is that if we have something that could either be in a register or in 5558 /// memory that use of the register could cause selection of *other* 5559 /// operands to fail: they might only succeed if we pick memory. Because of 5560 /// this the heuristic we use is: 5561 /// 5562 /// 1) If there is an 'other' constraint, and if the operand is valid for 5563 /// that constraint, use it. This makes us take advantage of 'i' 5564 /// constraints when available. 5565 /// 2) Otherwise, pick the most general constraint present. This prefers 5566 /// 'm' over 'r', for example. 5567 /// 5568 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5569 const TargetLowering &TLI, 5570 SDValue Op, SelectionDAG *DAG) { 5571 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5572 unsigned BestIdx = 0; 5573 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5574 int BestGenerality = -1; 5575 5576 // Loop over the options, keeping track of the most general one. 5577 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5578 TargetLowering::ConstraintType CType = 5579 TLI.getConstraintType(OpInfo.Codes[i]); 5580 5581 // Indirect 'other' or 'immediate' constraints are not allowed. 5582 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5583 CType == TargetLowering::C_Register || 5584 CType == TargetLowering::C_RegisterClass)) 5585 continue; 5586 5587 // If this is an 'other' or 'immediate' constraint, see if the operand is 5588 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5589 // the operand is an integer in the range [0..31] we want to use I (saving a 5590 // load of a register), otherwise we must use 'r'. 5591 if ((CType == TargetLowering::C_Other || 5592 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5593 assert(OpInfo.Codes[i].size() == 1 && 5594 "Unhandled multi-letter 'other' constraint"); 5595 std::vector<SDValue> ResultOps; 5596 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5597 ResultOps, *DAG); 5598 if (!ResultOps.empty()) { 5599 BestType = CType; 5600 BestIdx = i; 5601 break; 5602 } 5603 } 5604 5605 // Things with matching constraints can only be registers, per gcc 5606 // documentation. This mainly affects "g" constraints. 5607 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5608 continue; 5609 5610 // This constraint letter is more general than the previous one, use it. 5611 int Generality = getConstraintGenerality(CType); 5612 if (Generality > BestGenerality) { 5613 BestType = CType; 5614 BestIdx = i; 5615 BestGenerality = Generality; 5616 } 5617 } 5618 5619 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5620 OpInfo.ConstraintType = BestType; 5621 } 5622 5623 /// Determines the constraint code and constraint type to use for the specific 5624 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5625 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5626 SDValue Op, 5627 SelectionDAG *DAG) const { 5628 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5629 5630 // Single-letter constraints ('r') are very common. 5631 if (OpInfo.Codes.size() == 1) { 5632 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5633 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5634 } else { 5635 ChooseConstraint(OpInfo, *this, Op, DAG); 5636 } 5637 5638 // 'X' matches anything. 5639 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5640 // Constants are handled elsewhere. For Functions, the type here is the 5641 // type of the result, which is not what we want to look at; leave them 5642 // alone. 5643 Value *v = OpInfo.CallOperandVal; 5644 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5645 return; 5646 } 5647 5648 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5649 OpInfo.ConstraintCode = "i"; 5650 return; 5651 } 5652 5653 // Otherwise, try to resolve it to something we know about by looking at 5654 // the actual operand type. 5655 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5656 OpInfo.ConstraintCode = Repl; 5657 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5658 } 5659 } 5660 } 5661 5662 /// Given an exact SDIV by a constant, create a multiplication 5663 /// with the multiplicative inverse of the constant. 5664 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5665 const SDLoc &dl, SelectionDAG &DAG, 5666 SmallVectorImpl<SDNode *> &Created) { 5667 SDValue Op0 = N->getOperand(0); 5668 SDValue Op1 = N->getOperand(1); 5669 EVT VT = N->getValueType(0); 5670 EVT SVT = VT.getScalarType(); 5671 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5672 EVT ShSVT = ShVT.getScalarType(); 5673 5674 bool UseSRA = false; 5675 SmallVector<SDValue, 16> Shifts, Factors; 5676 5677 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5678 if (C->isZero()) 5679 return false; 5680 APInt Divisor = C->getAPIntValue(); 5681 unsigned Shift = Divisor.countTrailingZeros(); 5682 if (Shift) { 5683 Divisor.ashrInPlace(Shift); 5684 UseSRA = true; 5685 } 5686 // Calculate the multiplicative inverse, using Newton's method. 5687 APInt t; 5688 APInt Factor = Divisor; 5689 while ((t = Divisor * Factor) != 1) 5690 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5691 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5692 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5693 return true; 5694 }; 5695 5696 // Collect all magic values from the build vector. 5697 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5698 return SDValue(); 5699 5700 SDValue Shift, Factor; 5701 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5702 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5703 Factor = DAG.getBuildVector(VT, dl, Factors); 5704 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5705 assert(Shifts.size() == 1 && Factors.size() == 1 && 5706 "Expected matchUnaryPredicate to return one element for scalable " 5707 "vectors"); 5708 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5709 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5710 } else { 5711 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5712 Shift = Shifts[0]; 5713 Factor = Factors[0]; 5714 } 5715 5716 SDValue Res = Op0; 5717 5718 // Shift the value upfront if it is even, so the LSB is one. 5719 if (UseSRA) { 5720 // TODO: For UDIV use SRL instead of SRA. 5721 SDNodeFlags Flags; 5722 Flags.setExact(true); 5723 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5724 Created.push_back(Res.getNode()); 5725 } 5726 5727 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5728 } 5729 5730 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5731 SelectionDAG &DAG, 5732 SmallVectorImpl<SDNode *> &Created) const { 5733 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5735 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5736 return SDValue(N, 0); // Lower SDIV as SDIV 5737 return SDValue(); 5738 } 5739 5740 SDValue 5741 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5742 SelectionDAG &DAG, 5743 SmallVectorImpl<SDNode *> &Created) const { 5744 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5746 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5747 return SDValue(N, 0); // Lower SREM as SREM 5748 return SDValue(); 5749 } 5750 5751 /// Given an ISD::SDIV node expressing a divide by constant, 5752 /// return a DAG expression to select that will generate the same value by 5753 /// multiplying by a magic number. 5754 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5755 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5756 bool IsAfterLegalization, 5757 SmallVectorImpl<SDNode *> &Created) const { 5758 SDLoc dl(N); 5759 EVT VT = N->getValueType(0); 5760 EVT SVT = VT.getScalarType(); 5761 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5762 EVT ShSVT = ShVT.getScalarType(); 5763 unsigned EltBits = VT.getScalarSizeInBits(); 5764 EVT MulVT; 5765 5766 // Check to see if we can do this. 5767 // FIXME: We should be more aggressive here. 5768 if (!isTypeLegal(VT)) { 5769 // Limit this to simple scalars for now. 5770 if (VT.isVector() || !VT.isSimple()) 5771 return SDValue(); 5772 5773 // If this type will be promoted to a large enough type with a legal 5774 // multiply operation, we can go ahead and do this transform. 5775 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5776 return SDValue(); 5777 5778 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5779 if (MulVT.getSizeInBits() < (2 * EltBits) || 5780 !isOperationLegal(ISD::MUL, MulVT)) 5781 return SDValue(); 5782 } 5783 5784 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5785 if (N->getFlags().hasExact()) 5786 return BuildExactSDIV(*this, N, dl, DAG, Created); 5787 5788 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5789 5790 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5791 if (C->isZero()) 5792 return false; 5793 5794 const APInt &Divisor = C->getAPIntValue(); 5795 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5796 int NumeratorFactor = 0; 5797 int ShiftMask = -1; 5798 5799 if (Divisor.isOne() || Divisor.isAllOnes()) { 5800 // If d is +1/-1, we just multiply the numerator by +1/-1. 5801 NumeratorFactor = Divisor.getSExtValue(); 5802 magics.Magic = 0; 5803 magics.ShiftAmount = 0; 5804 ShiftMask = 0; 5805 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5806 // If d > 0 and m < 0, add the numerator. 5807 NumeratorFactor = 1; 5808 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5809 // If d < 0 and m > 0, subtract the numerator. 5810 NumeratorFactor = -1; 5811 } 5812 5813 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5814 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5815 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5816 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5817 return true; 5818 }; 5819 5820 SDValue N0 = N->getOperand(0); 5821 SDValue N1 = N->getOperand(1); 5822 5823 // Collect the shifts / magic values from each element. 5824 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5825 return SDValue(); 5826 5827 SDValue MagicFactor, Factor, Shift, ShiftMask; 5828 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5829 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5830 Factor = DAG.getBuildVector(VT, dl, Factors); 5831 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5832 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5833 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5834 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5835 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5836 "Expected matchUnaryPredicate to return one element for scalable " 5837 "vectors"); 5838 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5839 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5840 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5841 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5842 } else { 5843 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5844 MagicFactor = MagicFactors[0]; 5845 Factor = Factors[0]; 5846 Shift = Shifts[0]; 5847 ShiftMask = ShiftMasks[0]; 5848 } 5849 5850 // Multiply the numerator (operand 0) by the magic value. 5851 // FIXME: We should support doing a MUL in a wider type. 5852 auto GetMULHS = [&](SDValue X, SDValue Y) { 5853 // If the type isn't legal, use a wider mul of the the type calculated 5854 // earlier. 5855 if (!isTypeLegal(VT)) { 5856 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5857 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5858 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5859 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5860 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5861 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5862 } 5863 5864 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5865 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5866 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5867 SDValue LoHi = 5868 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5869 return SDValue(LoHi.getNode(), 1); 5870 } 5871 return SDValue(); 5872 }; 5873 5874 SDValue Q = GetMULHS(N0, MagicFactor); 5875 if (!Q) 5876 return SDValue(); 5877 5878 Created.push_back(Q.getNode()); 5879 5880 // (Optionally) Add/subtract the numerator using Factor. 5881 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5882 Created.push_back(Factor.getNode()); 5883 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5884 Created.push_back(Q.getNode()); 5885 5886 // Shift right algebraic by shift value. 5887 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5888 Created.push_back(Q.getNode()); 5889 5890 // Extract the sign bit, mask it and add it to the quotient. 5891 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5892 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5893 Created.push_back(T.getNode()); 5894 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5895 Created.push_back(T.getNode()); 5896 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5897 } 5898 5899 /// Given an ISD::UDIV node expressing a divide by constant, 5900 /// return a DAG expression to select that will generate the same value by 5901 /// multiplying by a magic number. 5902 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5903 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5904 bool IsAfterLegalization, 5905 SmallVectorImpl<SDNode *> &Created) const { 5906 SDLoc dl(N); 5907 EVT VT = N->getValueType(0); 5908 EVT SVT = VT.getScalarType(); 5909 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5910 EVT ShSVT = ShVT.getScalarType(); 5911 unsigned EltBits = VT.getScalarSizeInBits(); 5912 EVT MulVT; 5913 5914 // Check to see if we can do this. 5915 // FIXME: We should be more aggressive here. 5916 if (!isTypeLegal(VT)) { 5917 // Limit this to simple scalars for now. 5918 if (VT.isVector() || !VT.isSimple()) 5919 return SDValue(); 5920 5921 // If this type will be promoted to a large enough type with a legal 5922 // multiply operation, we can go ahead and do this transform. 5923 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5924 return SDValue(); 5925 5926 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5927 if (MulVT.getSizeInBits() < (2 * EltBits) || 5928 !isOperationLegal(ISD::MUL, MulVT)) 5929 return SDValue(); 5930 } 5931 5932 bool UseNPQ = false; 5933 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5934 5935 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5936 if (C->isZero()) 5937 return false; 5938 // FIXME: We should use a narrower constant when the upper 5939 // bits are known to be zero. 5940 const APInt& Divisor = C->getAPIntValue(); 5941 UnsignedDivisionByConstantInfo magics = 5942 UnsignedDivisionByConstantInfo::get(Divisor); 5943 unsigned PreShift = 0, PostShift = 0; 5944 5945 // If the divisor is even, we can avoid using the expensive fixup by 5946 // shifting the divided value upfront. 5947 if (magics.IsAdd && !Divisor[0]) { 5948 PreShift = Divisor.countTrailingZeros(); 5949 // Get magic number for the shifted divisor. 5950 magics = 5951 UnsignedDivisionByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5952 assert(!magics.IsAdd && "Should use cheap fixup now"); 5953 } 5954 5955 unsigned SelNPQ; 5956 if (!magics.IsAdd || Divisor.isOne()) { 5957 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5958 "We shouldn't generate an undefined shift!"); 5959 PostShift = magics.ShiftAmount; 5960 SelNPQ = false; 5961 } else { 5962 PostShift = magics.ShiftAmount - 1; 5963 SelNPQ = true; 5964 } 5965 5966 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5967 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5968 NPQFactors.push_back( 5969 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5970 : APInt::getZero(EltBits), 5971 dl, SVT)); 5972 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5973 UseNPQ |= SelNPQ; 5974 return true; 5975 }; 5976 5977 SDValue N0 = N->getOperand(0); 5978 SDValue N1 = N->getOperand(1); 5979 5980 // Collect the shifts/magic values from each element. 5981 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5982 return SDValue(); 5983 5984 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5985 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5986 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5987 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5988 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5989 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5990 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5991 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5992 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5993 "Expected matchUnaryPredicate to return one for scalable vectors"); 5994 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5995 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5996 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5997 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5998 } else { 5999 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6000 PreShift = PreShifts[0]; 6001 MagicFactor = MagicFactors[0]; 6002 PostShift = PostShifts[0]; 6003 } 6004 6005 SDValue Q = N0; 6006 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 6007 Created.push_back(Q.getNode()); 6008 6009 // FIXME: We should support doing a MUL in a wider type. 6010 auto GetMULHU = [&](SDValue X, SDValue Y) { 6011 // If the type isn't legal, use a wider mul of the the type calculated 6012 // earlier. 6013 if (!isTypeLegal(VT)) { 6014 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 6015 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 6016 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6017 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6018 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6019 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6020 } 6021 6022 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 6023 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 6024 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 6025 SDValue LoHi = 6026 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6027 return SDValue(LoHi.getNode(), 1); 6028 } 6029 return SDValue(); // No mulhu or equivalent 6030 }; 6031 6032 // Multiply the numerator (operand 0) by the magic value. 6033 Q = GetMULHU(Q, MagicFactor); 6034 if (!Q) 6035 return SDValue(); 6036 6037 Created.push_back(Q.getNode()); 6038 6039 if (UseNPQ) { 6040 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 6041 Created.push_back(NPQ.getNode()); 6042 6043 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 6044 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 6045 if (VT.isVector()) 6046 NPQ = GetMULHU(NPQ, NPQFactor); 6047 else 6048 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 6049 6050 Created.push_back(NPQ.getNode()); 6051 6052 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 6053 Created.push_back(Q.getNode()); 6054 } 6055 6056 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 6057 Created.push_back(Q.getNode()); 6058 6059 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6060 6061 SDValue One = DAG.getConstant(1, dl, VT); 6062 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 6063 return DAG.getSelect(dl, VT, IsOne, N0, Q); 6064 } 6065 6066 /// If all values in Values that *don't* match the predicate are same 'splat' 6067 /// value, then replace all values with that splat value. 6068 /// Else, if AlternativeReplacement was provided, then replace all values that 6069 /// do match predicate with AlternativeReplacement value. 6070 static void 6071 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6072 std::function<bool(SDValue)> Predicate, 6073 SDValue AlternativeReplacement = SDValue()) { 6074 SDValue Replacement; 6075 // Is there a value for which the Predicate does *NOT* match? What is it? 6076 auto SplatValue = llvm::find_if_not(Values, Predicate); 6077 if (SplatValue != Values.end()) { 6078 // Does Values consist only of SplatValue's and values matching Predicate? 6079 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6080 return Value == *SplatValue || Predicate(Value); 6081 })) // Then we shall replace values matching predicate with SplatValue. 6082 Replacement = *SplatValue; 6083 } 6084 if (!Replacement) { 6085 // Oops, we did not find the "baseline" splat value. 6086 if (!AlternativeReplacement) 6087 return; // Nothing to do. 6088 // Let's replace with provided value then. 6089 Replacement = AlternativeReplacement; 6090 } 6091 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6092 } 6093 6094 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6095 /// where the divisor is constant and the comparison target is zero, 6096 /// return a DAG expression that will generate the same comparison result 6097 /// using only multiplications, additions and shifts/rotations. 6098 /// Ref: "Hacker's Delight" 10-17. 6099 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6100 SDValue CompTargetNode, 6101 ISD::CondCode Cond, 6102 DAGCombinerInfo &DCI, 6103 const SDLoc &DL) const { 6104 SmallVector<SDNode *, 5> Built; 6105 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6106 DCI, DL, Built)) { 6107 for (SDNode *N : Built) 6108 DCI.AddToWorklist(N); 6109 return Folded; 6110 } 6111 6112 return SDValue(); 6113 } 6114 6115 SDValue 6116 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6117 SDValue CompTargetNode, ISD::CondCode Cond, 6118 DAGCombinerInfo &DCI, const SDLoc &DL, 6119 SmallVectorImpl<SDNode *> &Created) const { 6120 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6121 // - D must be constant, with D = D0 * 2^K where D0 is odd 6122 // - P is the multiplicative inverse of D0 modulo 2^W 6123 // - Q = floor(((2^W) - 1) / D) 6124 // where W is the width of the common type of N and D. 6125 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6126 "Only applicable for (in)equality comparisons."); 6127 6128 SelectionDAG &DAG = DCI.DAG; 6129 6130 EVT VT = REMNode.getValueType(); 6131 EVT SVT = VT.getScalarType(); 6132 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6133 EVT ShSVT = ShVT.getScalarType(); 6134 6135 // If MUL is unavailable, we cannot proceed in any case. 6136 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6137 return SDValue(); 6138 6139 bool ComparingWithAllZeros = true; 6140 bool AllComparisonsWithNonZerosAreTautological = true; 6141 bool HadTautologicalLanes = false; 6142 bool AllLanesAreTautological = true; 6143 bool HadEvenDivisor = false; 6144 bool AllDivisorsArePowerOfTwo = true; 6145 bool HadTautologicalInvertedLanes = false; 6146 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6147 6148 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6149 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6150 if (CDiv->isZero()) 6151 return false; 6152 6153 const APInt &D = CDiv->getAPIntValue(); 6154 const APInt &Cmp = CCmp->getAPIntValue(); 6155 6156 ComparingWithAllZeros &= Cmp.isZero(); 6157 6158 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6159 // if C2 is not less than C1, the comparison is always false. 6160 // But we will only be able to produce the comparison that will give the 6161 // opposive tautological answer. So this lane would need to be fixed up. 6162 bool TautologicalInvertedLane = D.ule(Cmp); 6163 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6164 6165 // If all lanes are tautological (either all divisors are ones, or divisor 6166 // is not greater than the constant we are comparing with), 6167 // we will prefer to avoid the fold. 6168 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6169 HadTautologicalLanes |= TautologicalLane; 6170 AllLanesAreTautological &= TautologicalLane; 6171 6172 // If we are comparing with non-zero, we need'll need to subtract said 6173 // comparison value from the LHS. But there is no point in doing that if 6174 // every lane where we are comparing with non-zero is tautological.. 6175 if (!Cmp.isZero()) 6176 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6177 6178 // Decompose D into D0 * 2^K 6179 unsigned K = D.countTrailingZeros(); 6180 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6181 APInt D0 = D.lshr(K); 6182 6183 // D is even if it has trailing zeros. 6184 HadEvenDivisor |= (K != 0); 6185 // D is a power-of-two if D0 is one. 6186 // If all divisors are power-of-two, we will prefer to avoid the fold. 6187 AllDivisorsArePowerOfTwo &= D0.isOne(); 6188 6189 // P = inv(D0, 2^W) 6190 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6191 unsigned W = D.getBitWidth(); 6192 APInt P = D0.zext(W + 1) 6193 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6194 .trunc(W); 6195 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6196 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6197 6198 // Q = floor((2^W - 1) u/ D) 6199 // R = ((2^W - 1) u% D) 6200 APInt Q, R; 6201 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6202 6203 // If we are comparing with zero, then that comparison constant is okay, 6204 // else it may need to be one less than that. 6205 if (Cmp.ugt(R)) 6206 Q -= 1; 6207 6208 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6209 "We are expecting that K is always less than all-ones for ShSVT"); 6210 6211 // If the lane is tautological the result can be constant-folded. 6212 if (TautologicalLane) { 6213 // Set P and K amount to a bogus values so we can try to splat them. 6214 P = 0; 6215 K = -1; 6216 // And ensure that comparison constant is tautological, 6217 // it will always compare true/false. 6218 Q = -1; 6219 } 6220 6221 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6222 KAmts.push_back( 6223 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6224 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6225 return true; 6226 }; 6227 6228 SDValue N = REMNode.getOperand(0); 6229 SDValue D = REMNode.getOperand(1); 6230 6231 // Collect the values from each element. 6232 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6233 return SDValue(); 6234 6235 // If all lanes are tautological, the result can be constant-folded. 6236 if (AllLanesAreTautological) 6237 return SDValue(); 6238 6239 // If this is a urem by a powers-of-two, avoid the fold since it can be 6240 // best implemented as a bit test. 6241 if (AllDivisorsArePowerOfTwo) 6242 return SDValue(); 6243 6244 SDValue PVal, KVal, QVal; 6245 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6246 if (HadTautologicalLanes) { 6247 // Try to turn PAmts into a splat, since we don't care about the values 6248 // that are currently '0'. If we can't, just keep '0'`s. 6249 turnVectorIntoSplatVector(PAmts, isNullConstant); 6250 // Try to turn KAmts into a splat, since we don't care about the values 6251 // that are currently '-1'. If we can't, change them to '0'`s. 6252 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6253 DAG.getConstant(0, DL, ShSVT)); 6254 } 6255 6256 PVal = DAG.getBuildVector(VT, DL, PAmts); 6257 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6258 QVal = DAG.getBuildVector(VT, DL, QAmts); 6259 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6260 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6261 "Expected matchBinaryPredicate to return one element for " 6262 "SPLAT_VECTORs"); 6263 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6264 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6265 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6266 } else { 6267 PVal = PAmts[0]; 6268 KVal = KAmts[0]; 6269 QVal = QAmts[0]; 6270 } 6271 6272 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6273 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6274 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6275 assert(CompTargetNode.getValueType() == N.getValueType() && 6276 "Expecting that the types on LHS and RHS of comparisons match."); 6277 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6278 } 6279 6280 // (mul N, P) 6281 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6282 Created.push_back(Op0.getNode()); 6283 6284 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6285 // divisors as a performance improvement, since rotating by 0 is a no-op. 6286 if (HadEvenDivisor) { 6287 // We need ROTR to do this. 6288 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6289 return SDValue(); 6290 // UREM: (rotr (mul N, P), K) 6291 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6292 Created.push_back(Op0.getNode()); 6293 } 6294 6295 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6296 SDValue NewCC = 6297 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6298 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6299 if (!HadTautologicalInvertedLanes) 6300 return NewCC; 6301 6302 // If any lanes previously compared always-false, the NewCC will give 6303 // always-true result for them, so we need to fixup those lanes. 6304 // Or the other way around for inequality predicate. 6305 assert(VT.isVector() && "Can/should only get here for vectors."); 6306 Created.push_back(NewCC.getNode()); 6307 6308 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6309 // if C2 is not less than C1, the comparison is always false. 6310 // But we have produced the comparison that will give the 6311 // opposive tautological answer. So these lanes would need to be fixed up. 6312 SDValue TautologicalInvertedChannels = 6313 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6314 Created.push_back(TautologicalInvertedChannels.getNode()); 6315 6316 // NOTE: we avoid letting illegal types through even if we're before legalize 6317 // ops – legalization has a hard time producing good code for this. 6318 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6319 // If we have a vector select, let's replace the comparison results in the 6320 // affected lanes with the correct tautological result. 6321 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6322 DL, SETCCVT, SETCCVT); 6323 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6324 Replacement, NewCC); 6325 } 6326 6327 // Else, we can just invert the comparison result in the appropriate lanes. 6328 // 6329 // NOTE: see the note above VSELECT above. 6330 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6331 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6332 TautologicalInvertedChannels); 6333 6334 return SDValue(); // Don't know how to lower. 6335 } 6336 6337 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6338 /// where the divisor is constant and the comparison target is zero, 6339 /// return a DAG expression that will generate the same comparison result 6340 /// using only multiplications, additions and shifts/rotations. 6341 /// Ref: "Hacker's Delight" 10-17. 6342 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6343 SDValue CompTargetNode, 6344 ISD::CondCode Cond, 6345 DAGCombinerInfo &DCI, 6346 const SDLoc &DL) const { 6347 SmallVector<SDNode *, 7> Built; 6348 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6349 DCI, DL, Built)) { 6350 assert(Built.size() <= 7 && "Max size prediction failed."); 6351 for (SDNode *N : Built) 6352 DCI.AddToWorklist(N); 6353 return Folded; 6354 } 6355 6356 return SDValue(); 6357 } 6358 6359 SDValue 6360 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6361 SDValue CompTargetNode, ISD::CondCode Cond, 6362 DAGCombinerInfo &DCI, const SDLoc &DL, 6363 SmallVectorImpl<SDNode *> &Created) const { 6364 // Fold: 6365 // (seteq/ne (srem N, D), 0) 6366 // To: 6367 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6368 // 6369 // - D must be constant, with D = D0 * 2^K where D0 is odd 6370 // - P is the multiplicative inverse of D0 modulo 2^W 6371 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6372 // - Q = floor((2 * A) / (2^K)) 6373 // where W is the width of the common type of N and D. 6374 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6375 "Only applicable for (in)equality comparisons."); 6376 6377 SelectionDAG &DAG = DCI.DAG; 6378 6379 EVT VT = REMNode.getValueType(); 6380 EVT SVT = VT.getScalarType(); 6381 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6382 EVT ShSVT = ShVT.getScalarType(); 6383 6384 // If we are after ops legalization, and MUL is unavailable, we can not 6385 // proceed. 6386 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6387 return SDValue(); 6388 6389 // TODO: Could support comparing with non-zero too. 6390 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6391 if (!CompTarget || !CompTarget->isZero()) 6392 return SDValue(); 6393 6394 bool HadIntMinDivisor = false; 6395 bool HadOneDivisor = false; 6396 bool AllDivisorsAreOnes = true; 6397 bool HadEvenDivisor = false; 6398 bool NeedToApplyOffset = false; 6399 bool AllDivisorsArePowerOfTwo = true; 6400 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6401 6402 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6403 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6404 if (C->isZero()) 6405 return false; 6406 6407 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6408 6409 // WARNING: this fold is only valid for positive divisors! 6410 APInt D = C->getAPIntValue(); 6411 if (D.isNegative()) 6412 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6413 6414 HadIntMinDivisor |= D.isMinSignedValue(); 6415 6416 // If all divisors are ones, we will prefer to avoid the fold. 6417 HadOneDivisor |= D.isOne(); 6418 AllDivisorsAreOnes &= D.isOne(); 6419 6420 // Decompose D into D0 * 2^K 6421 unsigned K = D.countTrailingZeros(); 6422 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6423 APInt D0 = D.lshr(K); 6424 6425 if (!D.isMinSignedValue()) { 6426 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6427 // we don't care about this lane in this fold, we'll special-handle it. 6428 HadEvenDivisor |= (K != 0); 6429 } 6430 6431 // D is a power-of-two if D0 is one. This includes INT_MIN. 6432 // If all divisors are power-of-two, we will prefer to avoid the fold. 6433 AllDivisorsArePowerOfTwo &= D0.isOne(); 6434 6435 // P = inv(D0, 2^W) 6436 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6437 unsigned W = D.getBitWidth(); 6438 APInt P = D0.zext(W + 1) 6439 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6440 .trunc(W); 6441 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6442 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6443 6444 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6445 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6446 A.clearLowBits(K); 6447 6448 if (!D.isMinSignedValue()) { 6449 // If divisor INT_MIN, then we don't care about this lane in this fold, 6450 // we'll special-handle it. 6451 NeedToApplyOffset |= A != 0; 6452 } 6453 6454 // Q = floor((2 * A) / (2^K)) 6455 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6456 6457 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6458 "We are expecting that A is always less than all-ones for SVT"); 6459 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6460 "We are expecting that K is always less than all-ones for ShSVT"); 6461 6462 // If the divisor is 1 the result can be constant-folded. Likewise, we 6463 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6464 if (D.isOne()) { 6465 // Set P, A and K to a bogus values so we can try to splat them. 6466 P = 0; 6467 A = -1; 6468 K = -1; 6469 6470 // x ?% 1 == 0 <--> true <--> x u<= -1 6471 Q = -1; 6472 } 6473 6474 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6475 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6476 KAmts.push_back( 6477 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6478 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6479 return true; 6480 }; 6481 6482 SDValue N = REMNode.getOperand(0); 6483 SDValue D = REMNode.getOperand(1); 6484 6485 // Collect the values from each element. 6486 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6487 return SDValue(); 6488 6489 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6490 if (AllDivisorsAreOnes) 6491 return SDValue(); 6492 6493 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6494 // since it can be best implemented as a bit test. 6495 if (AllDivisorsArePowerOfTwo) 6496 return SDValue(); 6497 6498 SDValue PVal, AVal, KVal, QVal; 6499 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6500 if (HadOneDivisor) { 6501 // Try to turn PAmts into a splat, since we don't care about the values 6502 // that are currently '0'. If we can't, just keep '0'`s. 6503 turnVectorIntoSplatVector(PAmts, isNullConstant); 6504 // Try to turn AAmts into a splat, since we don't care about the 6505 // values that are currently '-1'. If we can't, change them to '0'`s. 6506 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6507 DAG.getConstant(0, DL, SVT)); 6508 // Try to turn KAmts into a splat, since we don't care about the values 6509 // that are currently '-1'. If we can't, change them to '0'`s. 6510 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6511 DAG.getConstant(0, DL, ShSVT)); 6512 } 6513 6514 PVal = DAG.getBuildVector(VT, DL, PAmts); 6515 AVal = DAG.getBuildVector(VT, DL, AAmts); 6516 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6517 QVal = DAG.getBuildVector(VT, DL, QAmts); 6518 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6519 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6520 QAmts.size() == 1 && 6521 "Expected matchUnaryPredicate to return one element for scalable " 6522 "vectors"); 6523 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6524 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6525 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6526 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6527 } else { 6528 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6529 PVal = PAmts[0]; 6530 AVal = AAmts[0]; 6531 KVal = KAmts[0]; 6532 QVal = QAmts[0]; 6533 } 6534 6535 // (mul N, P) 6536 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6537 Created.push_back(Op0.getNode()); 6538 6539 if (NeedToApplyOffset) { 6540 // We need ADD to do this. 6541 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6542 return SDValue(); 6543 6544 // (add (mul N, P), A) 6545 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6546 Created.push_back(Op0.getNode()); 6547 } 6548 6549 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6550 // divisors as a performance improvement, since rotating by 0 is a no-op. 6551 if (HadEvenDivisor) { 6552 // We need ROTR to do this. 6553 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6554 return SDValue(); 6555 // SREM: (rotr (add (mul N, P), A), K) 6556 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6557 Created.push_back(Op0.getNode()); 6558 } 6559 6560 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6561 SDValue Fold = 6562 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6563 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6564 6565 // If we didn't have lanes with INT_MIN divisor, then we're done. 6566 if (!HadIntMinDivisor) 6567 return Fold; 6568 6569 // That fold is only valid for positive divisors. Which effectively means, 6570 // it is invalid for INT_MIN divisors. So if we have such a lane, 6571 // we must fix-up results for said lanes. 6572 assert(VT.isVector() && "Can/should only get here for vectors."); 6573 6574 // NOTE: we avoid letting illegal types through even if we're before legalize 6575 // ops – legalization has a hard time producing good code for the code that 6576 // follows. 6577 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6578 !isOperationLegalOrCustom(ISD::AND, VT) || 6579 !isOperationLegalOrCustom(Cond, VT) || 6580 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6581 return SDValue(); 6582 6583 Created.push_back(Fold.getNode()); 6584 6585 SDValue IntMin = DAG.getConstant( 6586 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6587 SDValue IntMax = DAG.getConstant( 6588 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6589 SDValue Zero = 6590 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6591 6592 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6593 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6594 Created.push_back(DivisorIsIntMin.getNode()); 6595 6596 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6597 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6598 Created.push_back(Masked.getNode()); 6599 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6600 Created.push_back(MaskedIsZero.getNode()); 6601 6602 // To produce final result we need to blend 2 vectors: 'SetCC' and 6603 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6604 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6605 // constant-folded, select can get lowered to a shuffle with constant mask. 6606 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6607 MaskedIsZero, Fold); 6608 6609 return Blended; 6610 } 6611 6612 bool TargetLowering:: 6613 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6614 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6615 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6616 "be a constant integer"); 6617 return true; 6618 } 6619 6620 return false; 6621 } 6622 6623 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6624 const DenormalMode &Mode) const { 6625 SDLoc DL(Op); 6626 EVT VT = Op.getValueType(); 6627 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6628 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6629 // Testing it with denormal inputs to avoid wrong estimate. 6630 if (Mode.Input == DenormalMode::IEEE) { 6631 // This is specifically a check for the handling of denormal inputs, 6632 // not the result. 6633 6634 // Test = fabs(X) < SmallestNormal 6635 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6636 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6637 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6638 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6639 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6640 } 6641 // Test = X == 0.0 6642 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6643 } 6644 6645 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6646 bool LegalOps, bool OptForSize, 6647 NegatibleCost &Cost, 6648 unsigned Depth) const { 6649 // fneg is removable even if it has multiple uses. 6650 if (Op.getOpcode() == ISD::FNEG) { 6651 Cost = NegatibleCost::Cheaper; 6652 return Op.getOperand(0); 6653 } 6654 6655 // Don't recurse exponentially. 6656 if (Depth > SelectionDAG::MaxRecursionDepth) 6657 return SDValue(); 6658 6659 // Pre-increment recursion depth for use in recursive calls. 6660 ++Depth; 6661 const SDNodeFlags Flags = Op->getFlags(); 6662 const TargetOptions &Options = DAG.getTarget().Options; 6663 EVT VT = Op.getValueType(); 6664 unsigned Opcode = Op.getOpcode(); 6665 6666 // Don't allow anything with multiple uses unless we know it is free. 6667 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6668 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6669 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6670 if (!IsFreeExtend) 6671 return SDValue(); 6672 } 6673 6674 auto RemoveDeadNode = [&](SDValue N) { 6675 if (N && N.getNode()->use_empty()) 6676 DAG.RemoveDeadNode(N.getNode()); 6677 }; 6678 6679 SDLoc DL(Op); 6680 6681 // Because getNegatedExpression can delete nodes we need a handle to keep 6682 // temporary nodes alive in case the recursion manages to create an identical 6683 // node. 6684 std::list<HandleSDNode> Handles; 6685 6686 switch (Opcode) { 6687 case ISD::ConstantFP: { 6688 // Don't invert constant FP values after legalization unless the target says 6689 // the negated constant is legal. 6690 bool IsOpLegal = 6691 isOperationLegal(ISD::ConstantFP, VT) || 6692 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6693 OptForSize); 6694 6695 if (LegalOps && !IsOpLegal) 6696 break; 6697 6698 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6699 V.changeSign(); 6700 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6701 6702 // If we already have the use of the negated floating constant, it is free 6703 // to negate it even it has multiple uses. 6704 if (!Op.hasOneUse() && CFP.use_empty()) 6705 break; 6706 Cost = NegatibleCost::Neutral; 6707 return CFP; 6708 } 6709 case ISD::BUILD_VECTOR: { 6710 // Only permit BUILD_VECTOR of constants. 6711 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6712 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6713 })) 6714 break; 6715 6716 bool IsOpLegal = 6717 (isOperationLegal(ISD::ConstantFP, VT) && 6718 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6719 llvm::all_of(Op->op_values(), [&](SDValue N) { 6720 return N.isUndef() || 6721 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6722 OptForSize); 6723 }); 6724 6725 if (LegalOps && !IsOpLegal) 6726 break; 6727 6728 SmallVector<SDValue, 4> Ops; 6729 for (SDValue C : Op->op_values()) { 6730 if (C.isUndef()) { 6731 Ops.push_back(C); 6732 continue; 6733 } 6734 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6735 V.changeSign(); 6736 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6737 } 6738 Cost = NegatibleCost::Neutral; 6739 return DAG.getBuildVector(VT, DL, Ops); 6740 } 6741 case ISD::FADD: { 6742 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6743 break; 6744 6745 // After operation legalization, it might not be legal to create new FSUBs. 6746 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6747 break; 6748 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6749 6750 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6751 NegatibleCost CostX = NegatibleCost::Expensive; 6752 SDValue NegX = 6753 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6754 // Prevent this node from being deleted by the next call. 6755 if (NegX) 6756 Handles.emplace_back(NegX); 6757 6758 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6759 NegatibleCost CostY = NegatibleCost::Expensive; 6760 SDValue NegY = 6761 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6762 6763 // We're done with the handles. 6764 Handles.clear(); 6765 6766 // Negate the X if its cost is less or equal than Y. 6767 if (NegX && (CostX <= CostY)) { 6768 Cost = CostX; 6769 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6770 if (NegY != N) 6771 RemoveDeadNode(NegY); 6772 return N; 6773 } 6774 6775 // Negate the Y if it is not expensive. 6776 if (NegY) { 6777 Cost = CostY; 6778 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6779 if (NegX != N) 6780 RemoveDeadNode(NegX); 6781 return N; 6782 } 6783 break; 6784 } 6785 case ISD::FSUB: { 6786 // We can't turn -(A-B) into B-A when we honor signed zeros. 6787 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6788 break; 6789 6790 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6791 // fold (fneg (fsub 0, Y)) -> Y 6792 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6793 if (C->isZero()) { 6794 Cost = NegatibleCost::Cheaper; 6795 return Y; 6796 } 6797 6798 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6799 Cost = NegatibleCost::Neutral; 6800 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6801 } 6802 case ISD::FMUL: 6803 case ISD::FDIV: { 6804 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6805 6806 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6807 NegatibleCost CostX = NegatibleCost::Expensive; 6808 SDValue NegX = 6809 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6810 // Prevent this node from being deleted by the next call. 6811 if (NegX) 6812 Handles.emplace_back(NegX); 6813 6814 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6815 NegatibleCost CostY = NegatibleCost::Expensive; 6816 SDValue NegY = 6817 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6818 6819 // We're done with the handles. 6820 Handles.clear(); 6821 6822 // Negate the X if its cost is less or equal than Y. 6823 if (NegX && (CostX <= CostY)) { 6824 Cost = CostX; 6825 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6826 if (NegY != N) 6827 RemoveDeadNode(NegY); 6828 return N; 6829 } 6830 6831 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6832 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6833 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6834 break; 6835 6836 // Negate the Y if it is not expensive. 6837 if (NegY) { 6838 Cost = CostY; 6839 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6840 if (NegX != N) 6841 RemoveDeadNode(NegX); 6842 return N; 6843 } 6844 break; 6845 } 6846 case ISD::FMA: 6847 case ISD::FMAD: { 6848 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6849 break; 6850 6851 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6852 NegatibleCost CostZ = NegatibleCost::Expensive; 6853 SDValue NegZ = 6854 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6855 // Give up if fail to negate the Z. 6856 if (!NegZ) 6857 break; 6858 6859 // Prevent this node from being deleted by the next two calls. 6860 Handles.emplace_back(NegZ); 6861 6862 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6863 NegatibleCost CostX = NegatibleCost::Expensive; 6864 SDValue NegX = 6865 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6866 // Prevent this node from being deleted by the next call. 6867 if (NegX) 6868 Handles.emplace_back(NegX); 6869 6870 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6871 NegatibleCost CostY = NegatibleCost::Expensive; 6872 SDValue NegY = 6873 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6874 6875 // We're done with the handles. 6876 Handles.clear(); 6877 6878 // Negate the X if its cost is less or equal than Y. 6879 if (NegX && (CostX <= CostY)) { 6880 Cost = std::min(CostX, CostZ); 6881 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6882 if (NegY != N) 6883 RemoveDeadNode(NegY); 6884 return N; 6885 } 6886 6887 // Negate the Y if it is not expensive. 6888 if (NegY) { 6889 Cost = std::min(CostY, CostZ); 6890 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6891 if (NegX != N) 6892 RemoveDeadNode(NegX); 6893 return N; 6894 } 6895 break; 6896 } 6897 6898 case ISD::FP_EXTEND: 6899 case ISD::FSIN: 6900 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6901 OptForSize, Cost, Depth)) 6902 return DAG.getNode(Opcode, DL, VT, NegV); 6903 break; 6904 case ISD::FP_ROUND: 6905 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6906 OptForSize, Cost, Depth)) 6907 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6908 break; 6909 } 6910 6911 return SDValue(); 6912 } 6913 6914 //===----------------------------------------------------------------------===// 6915 // Legalization Utilities 6916 //===----------------------------------------------------------------------===// 6917 6918 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6919 SDValue LHS, SDValue RHS, 6920 SmallVectorImpl<SDValue> &Result, 6921 EVT HiLoVT, SelectionDAG &DAG, 6922 MulExpansionKind Kind, SDValue LL, 6923 SDValue LH, SDValue RL, SDValue RH) const { 6924 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6925 Opcode == ISD::SMUL_LOHI); 6926 6927 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6928 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6929 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6930 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6931 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6932 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6933 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6934 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6935 6936 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6937 return false; 6938 6939 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6940 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6941 6942 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6943 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6944 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6945 6946 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6947 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6948 bool Signed) -> bool { 6949 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6950 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6951 Hi = SDValue(Lo.getNode(), 1); 6952 return true; 6953 } 6954 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6955 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6956 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6957 return true; 6958 } 6959 return false; 6960 }; 6961 6962 SDValue Lo, Hi; 6963 6964 if (!LL.getNode() && !RL.getNode() && 6965 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6966 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6967 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6968 } 6969 6970 if (!LL.getNode()) 6971 return false; 6972 6973 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6974 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6975 DAG.MaskedValueIsZero(RHS, HighMask)) { 6976 // The inputs are both zero-extended. 6977 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6978 Result.push_back(Lo); 6979 Result.push_back(Hi); 6980 if (Opcode != ISD::MUL) { 6981 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6982 Result.push_back(Zero); 6983 Result.push_back(Zero); 6984 } 6985 return true; 6986 } 6987 } 6988 6989 if (!VT.isVector() && Opcode == ISD::MUL && 6990 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6991 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6992 // The input values are both sign-extended. 6993 // TODO non-MUL case? 6994 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6995 Result.push_back(Lo); 6996 Result.push_back(Hi); 6997 return true; 6998 } 6999 } 7000 7001 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 7002 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 7003 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 7004 7005 if (!LH.getNode() && !RH.getNode() && 7006 isOperationLegalOrCustom(ISD::SRL, VT) && 7007 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7008 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 7009 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 7010 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 7011 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 7012 } 7013 7014 if (!LH.getNode()) 7015 return false; 7016 7017 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 7018 return false; 7019 7020 Result.push_back(Lo); 7021 7022 if (Opcode == ISD::MUL) { 7023 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 7024 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 7025 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 7026 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 7027 Result.push_back(Hi); 7028 return true; 7029 } 7030 7031 // Compute the full width result. 7032 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 7033 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 7034 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7035 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 7036 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 7037 }; 7038 7039 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7040 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 7041 return false; 7042 7043 // This is effectively the add part of a multiply-add of half-sized operands, 7044 // so it cannot overflow. 7045 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7046 7047 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 7048 return false; 7049 7050 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7051 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7052 7053 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 7054 isOperationLegalOrCustom(ISD::ADDE, VT)); 7055 if (UseGlue) 7056 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 7057 Merge(Lo, Hi)); 7058 else 7059 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 7060 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 7061 7062 SDValue Carry = Next.getValue(1); 7063 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7064 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7065 7066 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7067 return false; 7068 7069 if (UseGlue) 7070 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7071 Carry); 7072 else 7073 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7074 Zero, Carry); 7075 7076 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7077 7078 if (Opcode == ISD::SMUL_LOHI) { 7079 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7080 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7081 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7082 7083 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7084 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7085 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7086 } 7087 7088 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7089 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7090 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7091 return true; 7092 } 7093 7094 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7095 SelectionDAG &DAG, MulExpansionKind Kind, 7096 SDValue LL, SDValue LH, SDValue RL, 7097 SDValue RH) const { 7098 SmallVector<SDValue, 2> Result; 7099 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7100 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7101 DAG, Kind, LL, LH, RL, RH); 7102 if (Ok) { 7103 assert(Result.size() == 2); 7104 Lo = Result[0]; 7105 Hi = Result[1]; 7106 } 7107 return Ok; 7108 } 7109 7110 // Check that (every element of) Z is undef or not an exact multiple of BW. 7111 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7112 return ISD::matchUnaryPredicate( 7113 Z, 7114 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7115 true); 7116 } 7117 7118 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7119 SelectionDAG &DAG) const { 7120 EVT VT = Node->getValueType(0); 7121 7122 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7123 !isOperationLegalOrCustom(ISD::SRL, VT) || 7124 !isOperationLegalOrCustom(ISD::SUB, VT) || 7125 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7126 return SDValue(); 7127 7128 SDValue X = Node->getOperand(0); 7129 SDValue Y = Node->getOperand(1); 7130 SDValue Z = Node->getOperand(2); 7131 7132 unsigned BW = VT.getScalarSizeInBits(); 7133 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7134 SDLoc DL(SDValue(Node, 0)); 7135 7136 EVT ShVT = Z.getValueType(); 7137 7138 // If a funnel shift in the other direction is more supported, use it. 7139 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7140 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7141 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7142 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7143 // fshl X, Y, Z -> fshr X, Y, -Z 7144 // fshr X, Y, Z -> fshl X, Y, -Z 7145 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7146 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7147 } else { 7148 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7149 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7150 SDValue One = DAG.getConstant(1, DL, ShVT); 7151 if (IsFSHL) { 7152 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7153 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7154 } else { 7155 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7156 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7157 } 7158 Z = DAG.getNOT(DL, Z, ShVT); 7159 } 7160 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7161 } 7162 7163 SDValue ShX, ShY; 7164 SDValue ShAmt, InvShAmt; 7165 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7166 // fshl: X << C | Y >> (BW - C) 7167 // fshr: X << (BW - C) | Y >> C 7168 // where C = Z % BW is not zero 7169 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7170 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7171 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7172 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7173 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7174 } else { 7175 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7176 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7177 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7178 if (isPowerOf2_32(BW)) { 7179 // Z % BW -> Z & (BW - 1) 7180 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7181 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7182 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7183 } else { 7184 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7185 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7186 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7187 } 7188 7189 SDValue One = DAG.getConstant(1, DL, ShVT); 7190 if (IsFSHL) { 7191 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7192 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7193 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7194 } else { 7195 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7196 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7197 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7198 } 7199 } 7200 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7201 } 7202 7203 // TODO: Merge with expandFunnelShift. 7204 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7205 SelectionDAG &DAG) const { 7206 EVT VT = Node->getValueType(0); 7207 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7208 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7209 SDValue Op0 = Node->getOperand(0); 7210 SDValue Op1 = Node->getOperand(1); 7211 SDLoc DL(SDValue(Node, 0)); 7212 7213 EVT ShVT = Op1.getValueType(); 7214 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7215 7216 // If a rotate in the other direction is more supported, use it. 7217 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7218 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7219 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7220 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7221 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7222 } 7223 7224 if (!AllowVectorOps && VT.isVector() && 7225 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7226 !isOperationLegalOrCustom(ISD::SRL, VT) || 7227 !isOperationLegalOrCustom(ISD::SUB, VT) || 7228 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7229 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7230 return SDValue(); 7231 7232 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7233 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7234 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7235 SDValue ShVal; 7236 SDValue HsVal; 7237 if (isPowerOf2_32(EltSizeInBits)) { 7238 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7239 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7240 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7241 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7242 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7243 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7244 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7245 } else { 7246 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7247 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7248 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7249 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7250 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7251 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7252 SDValue One = DAG.getConstant(1, DL, ShVT); 7253 HsVal = 7254 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7255 } 7256 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7257 } 7258 7259 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7260 SelectionDAG &DAG) const { 7261 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7262 EVT VT = Node->getValueType(0); 7263 unsigned VTBits = VT.getScalarSizeInBits(); 7264 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7265 7266 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7267 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7268 SDValue ShOpLo = Node->getOperand(0); 7269 SDValue ShOpHi = Node->getOperand(1); 7270 SDValue ShAmt = Node->getOperand(2); 7271 EVT ShAmtVT = ShAmt.getValueType(); 7272 EVT ShAmtCCVT = 7273 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7274 SDLoc dl(Node); 7275 7276 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7277 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7278 // away during isel. 7279 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7280 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7281 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7282 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7283 : DAG.getConstant(0, dl, VT); 7284 7285 SDValue Tmp2, Tmp3; 7286 if (IsSHL) { 7287 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7288 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7289 } else { 7290 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7291 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7292 } 7293 7294 // If the shift amount is larger or equal than the width of a part we don't 7295 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7296 // values for large shift amounts. 7297 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7298 DAG.getConstant(VTBits, dl, ShAmtVT)); 7299 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7300 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7301 7302 if (IsSHL) { 7303 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7304 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7305 } else { 7306 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7307 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7308 } 7309 } 7310 7311 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7312 SelectionDAG &DAG) const { 7313 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7314 SDValue Src = Node->getOperand(OpNo); 7315 EVT SrcVT = Src.getValueType(); 7316 EVT DstVT = Node->getValueType(0); 7317 SDLoc dl(SDValue(Node, 0)); 7318 7319 // FIXME: Only f32 to i64 conversions are supported. 7320 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7321 return false; 7322 7323 if (Node->isStrictFPOpcode()) 7324 // When a NaN is converted to an integer a trap is allowed. We can't 7325 // use this expansion here because it would eliminate that trap. Other 7326 // traps are also allowed and cannot be eliminated. See 7327 // IEEE 754-2008 sec 5.8. 7328 return false; 7329 7330 // Expand f32 -> i64 conversion 7331 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7332 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7333 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7334 EVT IntVT = SrcVT.changeTypeToInteger(); 7335 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7336 7337 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7338 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7339 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7340 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7341 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7342 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7343 7344 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7345 7346 SDValue ExponentBits = DAG.getNode( 7347 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7348 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7349 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7350 7351 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7352 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7353 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7354 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7355 7356 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7357 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7358 DAG.getConstant(0x00800000, dl, IntVT)); 7359 7360 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7361 7362 R = DAG.getSelectCC( 7363 dl, Exponent, ExponentLoBit, 7364 DAG.getNode(ISD::SHL, dl, DstVT, R, 7365 DAG.getZExtOrTrunc( 7366 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7367 dl, IntShVT)), 7368 DAG.getNode(ISD::SRL, dl, DstVT, R, 7369 DAG.getZExtOrTrunc( 7370 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7371 dl, IntShVT)), 7372 ISD::SETGT); 7373 7374 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7375 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7376 7377 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7378 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7379 return true; 7380 } 7381 7382 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7383 SDValue &Chain, 7384 SelectionDAG &DAG) const { 7385 SDLoc dl(SDValue(Node, 0)); 7386 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7387 SDValue Src = Node->getOperand(OpNo); 7388 7389 EVT SrcVT = Src.getValueType(); 7390 EVT DstVT = Node->getValueType(0); 7391 EVT SetCCVT = 7392 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7393 EVT DstSetCCVT = 7394 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7395 7396 // Only expand vector types if we have the appropriate vector bit operations. 7397 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7398 ISD::FP_TO_SINT; 7399 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7400 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7401 return false; 7402 7403 // If the maximum float value is smaller then the signed integer range, 7404 // the destination signmask can't be represented by the float, so we can 7405 // just use FP_TO_SINT directly. 7406 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7407 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7408 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7409 if (APFloat::opOverflow & 7410 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7411 if (Node->isStrictFPOpcode()) { 7412 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7413 { Node->getOperand(0), Src }); 7414 Chain = Result.getValue(1); 7415 } else 7416 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7417 return true; 7418 } 7419 7420 // Don't expand it if there isn't cheap fsub instruction. 7421 if (!isOperationLegalOrCustom( 7422 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7423 return false; 7424 7425 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7426 SDValue Sel; 7427 7428 if (Node->isStrictFPOpcode()) { 7429 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7430 Node->getOperand(0), /*IsSignaling*/ true); 7431 Chain = Sel.getValue(1); 7432 } else { 7433 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7434 } 7435 7436 bool Strict = Node->isStrictFPOpcode() || 7437 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7438 7439 if (Strict) { 7440 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7441 // signmask then offset (the result of which should be fully representable). 7442 // Sel = Src < 0x8000000000000000 7443 // FltOfs = select Sel, 0, 0x8000000000000000 7444 // IntOfs = select Sel, 0, 0x8000000000000000 7445 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7446 7447 // TODO: Should any fast-math-flags be set for the FSUB? 7448 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7449 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7450 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7451 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7452 DAG.getConstant(0, dl, DstVT), 7453 DAG.getConstant(SignMask, dl, DstVT)); 7454 SDValue SInt; 7455 if (Node->isStrictFPOpcode()) { 7456 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7457 { Chain, Src, FltOfs }); 7458 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7459 { Val.getValue(1), Val }); 7460 Chain = SInt.getValue(1); 7461 } else { 7462 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7463 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7464 } 7465 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7466 } else { 7467 // Expand based on maximum range of FP_TO_SINT: 7468 // True = fp_to_sint(Src) 7469 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7470 // Result = select (Src < 0x8000000000000000), True, False 7471 7472 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7473 // TODO: Should any fast-math-flags be set for the FSUB? 7474 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7475 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7476 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7477 DAG.getConstant(SignMask, dl, DstVT)); 7478 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7479 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7480 } 7481 return true; 7482 } 7483 7484 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7485 SDValue &Chain, 7486 SelectionDAG &DAG) const { 7487 // This transform is not correct for converting 0 when rounding mode is set 7488 // to round toward negative infinity which will produce -0.0. So disable under 7489 // strictfp. 7490 if (Node->isStrictFPOpcode()) 7491 return false; 7492 7493 SDValue Src = Node->getOperand(0); 7494 EVT SrcVT = Src.getValueType(); 7495 EVT DstVT = Node->getValueType(0); 7496 7497 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7498 return false; 7499 7500 // Only expand vector types if we have the appropriate vector bit operations. 7501 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7502 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7503 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7504 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7505 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7506 return false; 7507 7508 SDLoc dl(SDValue(Node, 0)); 7509 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7510 7511 // Implementation of unsigned i64 to f64 following the algorithm in 7512 // __floatundidf in compiler_rt. This implementation performs rounding 7513 // correctly in all rounding modes with the exception of converting 0 7514 // when rounding toward negative infinity. In that case the fsub will produce 7515 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7516 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7517 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7518 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7519 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7520 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7521 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7522 7523 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7524 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7525 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7526 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7527 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7528 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7529 SDValue HiSub = 7530 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7531 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7532 return true; 7533 } 7534 7535 SDValue 7536 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7537 SelectionDAG &DAG) const { 7538 unsigned Opcode = Node->getOpcode(); 7539 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7540 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7541 "Wrong opcode"); 7542 7543 if (Node->getFlags().hasNoNaNs()) { 7544 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7545 SDValue Op1 = Node->getOperand(0); 7546 SDValue Op2 = Node->getOperand(1); 7547 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7548 // Copy FMF flags, but always set the no-signed-zeros flag 7549 // as this is implied by the FMINNUM/FMAXNUM semantics. 7550 SDNodeFlags Flags = Node->getFlags(); 7551 Flags.setNoSignedZeros(true); 7552 SelCC->setFlags(Flags); 7553 return SelCC; 7554 } 7555 7556 return SDValue(); 7557 } 7558 7559 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7560 SelectionDAG &DAG) const { 7561 SDLoc dl(Node); 7562 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7563 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7564 EVT VT = Node->getValueType(0); 7565 7566 if (VT.isScalableVector()) 7567 report_fatal_error( 7568 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7569 7570 if (isOperationLegalOrCustom(NewOp, VT)) { 7571 SDValue Quiet0 = Node->getOperand(0); 7572 SDValue Quiet1 = Node->getOperand(1); 7573 7574 if (!Node->getFlags().hasNoNaNs()) { 7575 // Insert canonicalizes if it's possible we need to quiet to get correct 7576 // sNaN behavior. 7577 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7578 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7579 Node->getFlags()); 7580 } 7581 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7582 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7583 Node->getFlags()); 7584 } 7585 } 7586 7587 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7588 } 7589 7590 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7591 // instead if there are no NaNs. 7592 if (Node->getFlags().hasNoNaNs()) { 7593 unsigned IEEE2018Op = 7594 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7595 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7596 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7597 Node->getOperand(1), Node->getFlags()); 7598 } 7599 } 7600 7601 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7602 return SelCC; 7603 7604 return SDValue(); 7605 } 7606 7607 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7608 unsigned Test, SDNodeFlags Flags, 7609 const SDLoc &DL, 7610 SelectionDAG &DAG) const { 7611 EVT OperandVT = Op.getValueType(); 7612 assert(OperandVT.isFloatingPoint()); 7613 7614 // Degenerated cases. 7615 if (Test == 0) 7616 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7617 if ((Test & fcAllFlags) == fcAllFlags) 7618 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7619 7620 // PPC double double is a pair of doubles, of which the higher part determines 7621 // the value class. 7622 if (OperandVT == MVT::ppcf128) { 7623 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7624 DAG.getConstant(1, DL, MVT::i32)); 7625 OperandVT = MVT::f64; 7626 } 7627 7628 // Some checks may be represented as inversion of simpler check, for example 7629 // "inf|normal|subnormal|zero" => !"nan". 7630 bool IsInverted = false; 7631 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7632 IsInverted = true; 7633 Test = InvertedCheck; 7634 } 7635 7636 // Floating-point type properties. 7637 EVT ScalarFloatVT = OperandVT.getScalarType(); 7638 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7639 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7640 bool IsF80 = (ScalarFloatVT == MVT::f80); 7641 7642 // Some checks can be implemented using float comparisons, if floating point 7643 // exceptions are ignored. 7644 if (Flags.hasNoFPExcept() && 7645 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7646 if (Test == fcZero) 7647 return DAG.getSetCC(DL, ResultVT, Op, 7648 DAG.getConstantFP(0.0, DL, OperandVT), 7649 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7650 if (Test == fcNan) 7651 return DAG.getSetCC(DL, ResultVT, Op, Op, 7652 IsInverted ? ISD::SETO : ISD::SETUO); 7653 } 7654 7655 // In the general case use integer operations. 7656 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7657 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7658 if (OperandVT.isVector()) 7659 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7660 OperandVT.getVectorElementCount()); 7661 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7662 7663 // Various masks. 7664 APInt SignBit = APInt::getSignMask(BitSize); 7665 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7666 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7667 const unsigned ExplicitIntBitInF80 = 63; 7668 APInt ExpMask = Inf; 7669 if (IsF80) 7670 ExpMask.clearBit(ExplicitIntBitInF80); 7671 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7672 APInt QNaNBitMask = 7673 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7674 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7675 7676 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7677 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7678 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7679 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7680 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7681 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7682 7683 SDValue Res; 7684 const auto appendResult = [&](SDValue PartialRes) { 7685 if (PartialRes) { 7686 if (Res) 7687 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7688 else 7689 Res = PartialRes; 7690 } 7691 }; 7692 7693 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7694 const auto getIntBitIsSet = [&]() -> SDValue { 7695 if (!IntBitIsSetV) { 7696 APInt IntBitMask(BitSize, 0); 7697 IntBitMask.setBit(ExplicitIntBitInF80); 7698 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7699 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7700 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7701 } 7702 return IntBitIsSetV; 7703 }; 7704 7705 // Split the value into sign bit and absolute value. 7706 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7707 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7708 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7709 7710 // Tests that involve more than one class should be processed first. 7711 SDValue PartialRes; 7712 7713 if (IsF80) 7714 ; // Detect finite numbers of f80 by checking individual classes because 7715 // they have different settings of the explicit integer bit. 7716 else if ((Test & fcFinite) == fcFinite) { 7717 // finite(V) ==> abs(V) < exp_mask 7718 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7719 Test &= ~fcFinite; 7720 } else if ((Test & fcFinite) == fcPosFinite) { 7721 // finite(V) && V > 0 ==> V < exp_mask 7722 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7723 Test &= ~fcPosFinite; 7724 } else if ((Test & fcFinite) == fcNegFinite) { 7725 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7726 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7727 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7728 Test &= ~fcNegFinite; 7729 } 7730 appendResult(PartialRes); 7731 7732 // Check for individual classes. 7733 7734 if (unsigned PartialCheck = Test & fcZero) { 7735 if (PartialCheck == fcPosZero) 7736 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7737 else if (PartialCheck == fcZero) 7738 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7739 else // ISD::fcNegZero 7740 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7741 appendResult(PartialRes); 7742 } 7743 7744 if (unsigned PartialCheck = Test & fcInf) { 7745 if (PartialCheck == fcPosInf) 7746 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7747 else if (PartialCheck == fcInf) 7748 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7749 else { // ISD::fcNegInf 7750 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7751 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7752 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7753 } 7754 appendResult(PartialRes); 7755 } 7756 7757 if (unsigned PartialCheck = Test & fcNan) { 7758 APInt InfWithQnanBit = Inf | QNaNBitMask; 7759 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7760 if (PartialCheck == fcNan) { 7761 // isnan(V) ==> abs(V) > int(inf) 7762 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7763 if (IsF80) { 7764 // Recognize unsupported values as NaNs for compatibility with glibc. 7765 // In them (exp(V)==0) == int_bit. 7766 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7767 SDValue ExpIsZero = 7768 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7769 SDValue IsPseudo = 7770 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7771 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7772 } 7773 } else if (PartialCheck == fcQNan) { 7774 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7775 PartialRes = 7776 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7777 } else { // ISD::fcSNan 7778 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7779 // abs(V) < (unsigned(Inf) | quiet_bit) 7780 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7781 SDValue IsNotQnan = 7782 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7783 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7784 } 7785 appendResult(PartialRes); 7786 } 7787 7788 if (unsigned PartialCheck = Test & fcSubnormal) { 7789 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7790 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7791 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7792 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7793 SDValue VMinusOneV = 7794 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7795 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7796 if (PartialCheck == fcNegSubnormal) 7797 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7798 appendResult(PartialRes); 7799 } 7800 7801 if (unsigned PartialCheck = Test & fcNormal) { 7802 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7803 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7804 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7805 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7806 APInt ExpLimit = ExpMask - ExpLSB; 7807 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7808 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7809 if (PartialCheck == fcNegNormal) 7810 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7811 else if (PartialCheck == fcPosNormal) { 7812 SDValue PosSignV = 7813 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7814 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7815 } 7816 if (IsF80) 7817 PartialRes = 7818 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7819 appendResult(PartialRes); 7820 } 7821 7822 if (!Res) 7823 return DAG.getConstant(IsInverted, DL, ResultVT); 7824 if (IsInverted) 7825 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7826 return Res; 7827 } 7828 7829 // Only expand vector types if we have the appropriate vector bit operations. 7830 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7831 assert(VT.isVector() && "Expected vector type"); 7832 unsigned Len = VT.getScalarSizeInBits(); 7833 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7834 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7835 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7836 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7837 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7838 } 7839 7840 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7841 SDLoc dl(Node); 7842 EVT VT = Node->getValueType(0); 7843 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7844 SDValue Op = Node->getOperand(0); 7845 unsigned Len = VT.getScalarSizeInBits(); 7846 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7847 7848 // TODO: Add support for irregular type lengths. 7849 if (!(Len <= 128 && Len % 8 == 0)) 7850 return SDValue(); 7851 7852 // Only expand vector types if we have the appropriate vector bit operations. 7853 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7854 return SDValue(); 7855 7856 // This is the "best" algorithm from 7857 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7858 SDValue Mask55 = 7859 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7860 SDValue Mask33 = 7861 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7862 SDValue Mask0F = 7863 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7864 7865 // v = v - ((v >> 1) & 0x55555555...) 7866 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7867 DAG.getNode(ISD::AND, dl, VT, 7868 DAG.getNode(ISD::SRL, dl, VT, Op, 7869 DAG.getConstant(1, dl, ShVT)), 7870 Mask55)); 7871 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7872 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7873 DAG.getNode(ISD::AND, dl, VT, 7874 DAG.getNode(ISD::SRL, dl, VT, Op, 7875 DAG.getConstant(2, dl, ShVT)), 7876 Mask33)); 7877 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7878 Op = DAG.getNode(ISD::AND, dl, VT, 7879 DAG.getNode(ISD::ADD, dl, VT, Op, 7880 DAG.getNode(ISD::SRL, dl, VT, Op, 7881 DAG.getConstant(4, dl, ShVT))), 7882 Mask0F); 7883 7884 if (Len <= 8) 7885 return Op; 7886 7887 // Avoid the multiply if we only have 2 bytes to add. 7888 // TODO: Only doing this for scalars because vectors weren't as obviously 7889 // improved. 7890 if (Len == 16 && !VT.isVector()) { 7891 // v = (v + (v >> 8)) & 0x00FF; 7892 return DAG.getNode(ISD::AND, dl, VT, 7893 DAG.getNode(ISD::ADD, dl, VT, Op, 7894 DAG.getNode(ISD::SRL, dl, VT, Op, 7895 DAG.getConstant(8, dl, ShVT))), 7896 DAG.getConstant(0xFF, dl, VT)); 7897 } 7898 7899 // v = (v * 0x01010101...) >> (Len - 8) 7900 SDValue Mask01 = 7901 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7902 return DAG.getNode(ISD::SRL, dl, VT, 7903 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7904 DAG.getConstant(Len - 8, dl, ShVT)); 7905 } 7906 7907 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7908 SDLoc dl(Node); 7909 EVT VT = Node->getValueType(0); 7910 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7911 SDValue Op = Node->getOperand(0); 7912 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7913 7914 // If the non-ZERO_UNDEF version is supported we can use that instead. 7915 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7916 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7917 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7918 7919 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7920 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7921 EVT SetCCVT = 7922 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7923 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7924 SDValue Zero = DAG.getConstant(0, dl, VT); 7925 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7926 return DAG.getSelect(dl, VT, SrcIsZero, 7927 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7928 } 7929 7930 // Only expand vector types if we have the appropriate vector bit operations. 7931 // This includes the operations needed to expand CTPOP if it isn't supported. 7932 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7933 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7934 !canExpandVectorCTPOP(*this, VT)) || 7935 !isOperationLegalOrCustom(ISD::SRL, VT) || 7936 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7937 return SDValue(); 7938 7939 // for now, we do this: 7940 // x = x | (x >> 1); 7941 // x = x | (x >> 2); 7942 // ... 7943 // x = x | (x >>16); 7944 // x = x | (x >>32); // for 64-bit input 7945 // return popcount(~x); 7946 // 7947 // Ref: "Hacker's Delight" by Henry Warren 7948 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 7949 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7950 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7951 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7952 } 7953 Op = DAG.getNOT(dl, Op, VT); 7954 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7955 } 7956 7957 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7958 SDLoc dl(Node); 7959 EVT VT = Node->getValueType(0); 7960 SDValue Op = Node->getOperand(0); 7961 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7962 7963 // If the non-ZERO_UNDEF version is supported we can use that instead. 7964 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7965 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7966 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7967 7968 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7969 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7970 EVT SetCCVT = 7971 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7972 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7973 SDValue Zero = DAG.getConstant(0, dl, VT); 7974 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7975 return DAG.getSelect(dl, VT, SrcIsZero, 7976 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7977 } 7978 7979 // Only expand vector types if we have the appropriate vector bit operations. 7980 // This includes the operations needed to expand CTPOP if it isn't supported. 7981 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7982 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7983 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7984 !canExpandVectorCTPOP(*this, VT)) || 7985 !isOperationLegalOrCustom(ISD::SUB, VT) || 7986 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7987 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7988 return SDValue(); 7989 7990 // for now, we use: { return popcount(~x & (x - 1)); } 7991 // unless the target has ctlz but not ctpop, in which case we use: 7992 // { return 32 - nlz(~x & (x-1)); } 7993 // Ref: "Hacker's Delight" by Henry Warren 7994 SDValue Tmp = DAG.getNode( 7995 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7996 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7997 7998 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7999 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 8000 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 8001 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 8002 } 8003 8004 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 8005 } 8006 8007 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 8008 bool IsNegative) const { 8009 SDLoc dl(N); 8010 EVT VT = N->getValueType(0); 8011 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8012 SDValue Op = N->getOperand(0); 8013 8014 // abs(x) -> smax(x,sub(0,x)) 8015 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 8016 isOperationLegal(ISD::SMAX, VT)) { 8017 SDValue Zero = DAG.getConstant(0, dl, VT); 8018 return DAG.getNode(ISD::SMAX, dl, VT, Op, 8019 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8020 } 8021 8022 // abs(x) -> umin(x,sub(0,x)) 8023 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 8024 isOperationLegal(ISD::UMIN, VT)) { 8025 SDValue Zero = DAG.getConstant(0, dl, VT); 8026 Op = DAG.getFreeze(Op); 8027 return DAG.getNode(ISD::UMIN, dl, VT, Op, 8028 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8029 } 8030 8031 // 0 - abs(x) -> smin(x, sub(0,x)) 8032 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 8033 isOperationLegal(ISD::SMIN, VT)) { 8034 Op = DAG.getFreeze(Op); 8035 SDValue Zero = DAG.getConstant(0, dl, VT); 8036 return DAG.getNode(ISD::SMIN, dl, VT, Op, 8037 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8038 } 8039 8040 // Only expand vector types if we have the appropriate vector operations. 8041 if (VT.isVector() && 8042 (!isOperationLegalOrCustom(ISD::SRA, VT) || 8043 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 8044 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 8045 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 8046 return SDValue(); 8047 8048 Op = DAG.getFreeze(Op); 8049 SDValue Shift = 8050 DAG.getNode(ISD::SRA, dl, VT, Op, 8051 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 8052 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 8053 8054 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 8055 if (!IsNegative) 8056 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 8057 8058 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 8059 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 8060 } 8061 8062 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 8063 SDLoc dl(N); 8064 EVT VT = N->getValueType(0); 8065 SDValue Op = N->getOperand(0); 8066 8067 if (!VT.isSimple()) 8068 return SDValue(); 8069 8070 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8071 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 8072 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 8073 default: 8074 return SDValue(); 8075 case MVT::i16: 8076 // Use a rotate by 8. This can be further expanded if necessary. 8077 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8078 case MVT::i32: 8079 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8080 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8081 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8082 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8083 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8084 DAG.getConstant(0xFF0000, dl, VT)); 8085 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 8086 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8087 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8088 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8089 case MVT::i64: 8090 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8091 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8092 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8093 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8094 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8095 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8096 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8097 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8098 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 8099 DAG.getConstant(255ULL<<48, dl, VT)); 8100 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 8101 DAG.getConstant(255ULL<<40, dl, VT)); 8102 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 8103 DAG.getConstant(255ULL<<32, dl, VT)); 8104 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 8105 DAG.getConstant(255ULL<<24, dl, VT)); 8106 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8107 DAG.getConstant(255ULL<<16, dl, VT)); 8108 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 8109 DAG.getConstant(255ULL<<8 , dl, VT)); 8110 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 8111 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 8112 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8113 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8114 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 8115 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8116 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 8117 } 8118 } 8119 8120 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 8121 SDLoc dl(N); 8122 EVT VT = N->getValueType(0); 8123 SDValue Op = N->getOperand(0); 8124 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8125 unsigned Sz = VT.getScalarSizeInBits(); 8126 8127 SDValue Tmp, Tmp2, Tmp3; 8128 8129 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 8130 // and finally the i1 pairs. 8131 // TODO: We can easily support i4/i2 legal types if any target ever does. 8132 if (Sz >= 8 && isPowerOf2_32(Sz)) { 8133 // Create the masks - repeating the pattern every byte. 8134 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 8135 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 8136 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 8137 8138 // BSWAP if the type is wider than a single byte. 8139 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 8140 8141 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 8142 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 8143 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 8144 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 8145 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8146 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8147 8148 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8149 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8150 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8151 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8152 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8153 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8154 8155 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8156 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8157 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8158 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8159 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8160 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8161 return Tmp; 8162 } 8163 8164 Tmp = DAG.getConstant(0, dl, VT); 8165 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8166 if (I < J) 8167 Tmp2 = 8168 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8169 else 8170 Tmp2 = 8171 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8172 8173 APInt Shift(Sz, 1); 8174 Shift <<= J; 8175 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8176 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8177 } 8178 8179 return Tmp; 8180 } 8181 8182 std::pair<SDValue, SDValue> 8183 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8184 SelectionDAG &DAG) const { 8185 SDLoc SL(LD); 8186 SDValue Chain = LD->getChain(); 8187 SDValue BasePTR = LD->getBasePtr(); 8188 EVT SrcVT = LD->getMemoryVT(); 8189 EVT DstVT = LD->getValueType(0); 8190 ISD::LoadExtType ExtType = LD->getExtensionType(); 8191 8192 if (SrcVT.isScalableVector()) 8193 report_fatal_error("Cannot scalarize scalable vector loads"); 8194 8195 unsigned NumElem = SrcVT.getVectorNumElements(); 8196 8197 EVT SrcEltVT = SrcVT.getScalarType(); 8198 EVT DstEltVT = DstVT.getScalarType(); 8199 8200 // A vector must always be stored in memory as-is, i.e. without any padding 8201 // between the elements, since various code depend on it, e.g. in the 8202 // handling of a bitcast of a vector type to int, which may be done with a 8203 // vector store followed by an integer load. A vector that does not have 8204 // elements that are byte-sized must therefore be stored as an integer 8205 // built out of the extracted vector elements. 8206 if (!SrcEltVT.isByteSized()) { 8207 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8208 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8209 8210 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8211 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8212 8213 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8214 SDValue SrcEltBitMask = DAG.getConstant( 8215 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8216 8217 // Load the whole vector and avoid masking off the top bits as it makes 8218 // the codegen worse. 8219 SDValue Load = 8220 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8221 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8222 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8223 8224 SmallVector<SDValue, 8> Vals; 8225 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8226 unsigned ShiftIntoIdx = 8227 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8228 SDValue ShiftAmount = 8229 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8230 LoadVT, SL, /*LegalTypes=*/false); 8231 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8232 SDValue Elt = 8233 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8234 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8235 8236 if (ExtType != ISD::NON_EXTLOAD) { 8237 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8238 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8239 } 8240 8241 Vals.push_back(Scalar); 8242 } 8243 8244 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8245 return std::make_pair(Value, Load.getValue(1)); 8246 } 8247 8248 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8249 assert(SrcEltVT.isByteSized()); 8250 8251 SmallVector<SDValue, 8> Vals; 8252 SmallVector<SDValue, 8> LoadChains; 8253 8254 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8255 SDValue ScalarLoad = 8256 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8257 LD->getPointerInfo().getWithOffset(Idx * Stride), 8258 SrcEltVT, LD->getOriginalAlign(), 8259 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8260 8261 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8262 8263 Vals.push_back(ScalarLoad.getValue(0)); 8264 LoadChains.push_back(ScalarLoad.getValue(1)); 8265 } 8266 8267 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8268 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8269 8270 return std::make_pair(Value, NewChain); 8271 } 8272 8273 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8274 SelectionDAG &DAG) const { 8275 SDLoc SL(ST); 8276 8277 SDValue Chain = ST->getChain(); 8278 SDValue BasePtr = ST->getBasePtr(); 8279 SDValue Value = ST->getValue(); 8280 EVT StVT = ST->getMemoryVT(); 8281 8282 if (StVT.isScalableVector()) 8283 report_fatal_error("Cannot scalarize scalable vector stores"); 8284 8285 // The type of the data we want to save 8286 EVT RegVT = Value.getValueType(); 8287 EVT RegSclVT = RegVT.getScalarType(); 8288 8289 // The type of data as saved in memory. 8290 EVT MemSclVT = StVT.getScalarType(); 8291 8292 unsigned NumElem = StVT.getVectorNumElements(); 8293 8294 // A vector must always be stored in memory as-is, i.e. without any padding 8295 // between the elements, since various code depend on it, e.g. in the 8296 // handling of a bitcast of a vector type to int, which may be done with a 8297 // vector store followed by an integer load. A vector that does not have 8298 // elements that are byte-sized must therefore be stored as an integer 8299 // built out of the extracted vector elements. 8300 if (!MemSclVT.isByteSized()) { 8301 unsigned NumBits = StVT.getSizeInBits(); 8302 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8303 8304 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8305 8306 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8307 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8308 DAG.getVectorIdxConstant(Idx, SL)); 8309 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8310 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8311 unsigned ShiftIntoIdx = 8312 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8313 SDValue ShiftAmount = 8314 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8315 SDValue ShiftedElt = 8316 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8317 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8318 } 8319 8320 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8321 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8322 ST->getAAInfo()); 8323 } 8324 8325 // Store Stride in bytes 8326 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8327 assert(Stride && "Zero stride!"); 8328 // Extract each of the elements from the original vector and save them into 8329 // memory individually. 8330 SmallVector<SDValue, 8> Stores; 8331 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8332 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8333 DAG.getVectorIdxConstant(Idx, SL)); 8334 8335 SDValue Ptr = 8336 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8337 8338 // This scalar TruncStore may be illegal, but we legalize it later. 8339 SDValue Store = DAG.getTruncStore( 8340 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8341 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8342 ST->getAAInfo()); 8343 8344 Stores.push_back(Store); 8345 } 8346 8347 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8348 } 8349 8350 std::pair<SDValue, SDValue> 8351 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8352 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8353 "unaligned indexed loads not implemented!"); 8354 SDValue Chain = LD->getChain(); 8355 SDValue Ptr = LD->getBasePtr(); 8356 EVT VT = LD->getValueType(0); 8357 EVT LoadedVT = LD->getMemoryVT(); 8358 SDLoc dl(LD); 8359 auto &MF = DAG.getMachineFunction(); 8360 8361 if (VT.isFloatingPoint() || VT.isVector()) { 8362 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8363 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8364 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8365 LoadedVT.isVector()) { 8366 // Scalarize the load and let the individual components be handled. 8367 return scalarizeVectorLoad(LD, DAG); 8368 } 8369 8370 // Expand to a (misaligned) integer load of the same size, 8371 // then bitconvert to floating point or vector. 8372 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8373 LD->getMemOperand()); 8374 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8375 if (LoadedVT != VT) 8376 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8377 ISD::ANY_EXTEND, dl, VT, Result); 8378 8379 return std::make_pair(Result, newLoad.getValue(1)); 8380 } 8381 8382 // Copy the value to a (aligned) stack slot using (unaligned) integer 8383 // loads and stores, then do a (aligned) load from the stack slot. 8384 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8385 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8386 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8387 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8388 8389 // Make sure the stack slot is also aligned for the register type. 8390 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8391 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8392 SmallVector<SDValue, 8> Stores; 8393 SDValue StackPtr = StackBase; 8394 unsigned Offset = 0; 8395 8396 EVT PtrVT = Ptr.getValueType(); 8397 EVT StackPtrVT = StackPtr.getValueType(); 8398 8399 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8400 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8401 8402 // Do all but one copies using the full register width. 8403 for (unsigned i = 1; i < NumRegs; i++) { 8404 // Load one integer register's worth from the original location. 8405 SDValue Load = DAG.getLoad( 8406 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8407 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8408 LD->getAAInfo()); 8409 // Follow the load with a store to the stack slot. Remember the store. 8410 Stores.push_back(DAG.getStore( 8411 Load.getValue(1), dl, Load, StackPtr, 8412 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8413 // Increment the pointers. 8414 Offset += RegBytes; 8415 8416 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8417 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8418 } 8419 8420 // The last copy may be partial. Do an extending load. 8421 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8422 8 * (LoadedBytes - Offset)); 8423 SDValue Load = 8424 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8425 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8426 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8427 LD->getAAInfo()); 8428 // Follow the load with a store to the stack slot. Remember the store. 8429 // On big-endian machines this requires a truncating store to ensure 8430 // that the bits end up in the right place. 8431 Stores.push_back(DAG.getTruncStore( 8432 Load.getValue(1), dl, Load, StackPtr, 8433 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8434 8435 // The order of the stores doesn't matter - say it with a TokenFactor. 8436 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8437 8438 // Finally, perform the original load only redirected to the stack slot. 8439 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8440 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8441 LoadedVT); 8442 8443 // Callers expect a MERGE_VALUES node. 8444 return std::make_pair(Load, TF); 8445 } 8446 8447 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8448 "Unaligned load of unsupported type."); 8449 8450 // Compute the new VT that is half the size of the old one. This is an 8451 // integer MVT. 8452 unsigned NumBits = LoadedVT.getSizeInBits(); 8453 EVT NewLoadedVT; 8454 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8455 NumBits >>= 1; 8456 8457 Align Alignment = LD->getOriginalAlign(); 8458 unsigned IncrementSize = NumBits / 8; 8459 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8460 8461 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8462 if (HiExtType == ISD::NON_EXTLOAD) 8463 HiExtType = ISD::ZEXTLOAD; 8464 8465 // Load the value in two parts 8466 SDValue Lo, Hi; 8467 if (DAG.getDataLayout().isLittleEndian()) { 8468 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8469 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8470 LD->getAAInfo()); 8471 8472 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8473 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8474 LD->getPointerInfo().getWithOffset(IncrementSize), 8475 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8476 LD->getAAInfo()); 8477 } else { 8478 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8479 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8480 LD->getAAInfo()); 8481 8482 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8483 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8484 LD->getPointerInfo().getWithOffset(IncrementSize), 8485 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8486 LD->getAAInfo()); 8487 } 8488 8489 // aggregate the two parts 8490 SDValue ShiftAmount = 8491 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8492 DAG.getDataLayout())); 8493 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8494 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8495 8496 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8497 Hi.getValue(1)); 8498 8499 return std::make_pair(Result, TF); 8500 } 8501 8502 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8503 SelectionDAG &DAG) const { 8504 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8505 "unaligned indexed stores not implemented!"); 8506 SDValue Chain = ST->getChain(); 8507 SDValue Ptr = ST->getBasePtr(); 8508 SDValue Val = ST->getValue(); 8509 EVT VT = Val.getValueType(); 8510 Align Alignment = ST->getOriginalAlign(); 8511 auto &MF = DAG.getMachineFunction(); 8512 EVT StoreMemVT = ST->getMemoryVT(); 8513 8514 SDLoc dl(ST); 8515 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8516 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8517 if (isTypeLegal(intVT)) { 8518 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8519 StoreMemVT.isVector()) { 8520 // Scalarize the store and let the individual components be handled. 8521 SDValue Result = scalarizeVectorStore(ST, DAG); 8522 return Result; 8523 } 8524 // Expand to a bitconvert of the value to the integer type of the 8525 // same size, then a (misaligned) int store. 8526 // FIXME: Does not handle truncating floating point stores! 8527 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8528 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8529 Alignment, ST->getMemOperand()->getFlags()); 8530 return Result; 8531 } 8532 // Do a (aligned) store to a stack slot, then copy from the stack slot 8533 // to the final destination using (unaligned) integer loads and stores. 8534 MVT RegVT = getRegisterType( 8535 *DAG.getContext(), 8536 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8537 EVT PtrVT = Ptr.getValueType(); 8538 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8539 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8540 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8541 8542 // Make sure the stack slot is also aligned for the register type. 8543 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8544 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8545 8546 // Perform the original store, only redirected to the stack slot. 8547 SDValue Store = DAG.getTruncStore( 8548 Chain, dl, Val, StackPtr, 8549 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8550 8551 EVT StackPtrVT = StackPtr.getValueType(); 8552 8553 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8554 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8555 SmallVector<SDValue, 8> Stores; 8556 unsigned Offset = 0; 8557 8558 // Do all but one copies using the full register width. 8559 for (unsigned i = 1; i < NumRegs; i++) { 8560 // Load one integer register's worth from the stack slot. 8561 SDValue Load = DAG.getLoad( 8562 RegVT, dl, Store, StackPtr, 8563 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8564 // Store it to the final location. Remember the store. 8565 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8566 ST->getPointerInfo().getWithOffset(Offset), 8567 ST->getOriginalAlign(), 8568 ST->getMemOperand()->getFlags())); 8569 // Increment the pointers. 8570 Offset += RegBytes; 8571 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8572 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8573 } 8574 8575 // The last store may be partial. Do a truncating store. On big-endian 8576 // machines this requires an extending load from the stack slot to ensure 8577 // that the bits are in the right place. 8578 EVT LoadMemVT = 8579 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8580 8581 // Load from the stack slot. 8582 SDValue Load = DAG.getExtLoad( 8583 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8584 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8585 8586 Stores.push_back( 8587 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8588 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8589 ST->getOriginalAlign(), 8590 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8591 // The order of the stores doesn't matter - say it with a TokenFactor. 8592 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8593 return Result; 8594 } 8595 8596 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8597 "Unaligned store of unknown type."); 8598 // Get the half-size VT 8599 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8600 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8601 unsigned IncrementSize = NumBits / 8; 8602 8603 // Divide the stored value in two parts. 8604 SDValue ShiftAmount = DAG.getConstant( 8605 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8606 SDValue Lo = Val; 8607 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8608 8609 // Store the two parts 8610 SDValue Store1, Store2; 8611 Store1 = DAG.getTruncStore(Chain, dl, 8612 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8613 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8614 ST->getMemOperand()->getFlags()); 8615 8616 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8617 Store2 = DAG.getTruncStore( 8618 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8619 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8620 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8621 8622 SDValue Result = 8623 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8624 return Result; 8625 } 8626 8627 SDValue 8628 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8629 const SDLoc &DL, EVT DataVT, 8630 SelectionDAG &DAG, 8631 bool IsCompressedMemory) const { 8632 SDValue Increment; 8633 EVT AddrVT = Addr.getValueType(); 8634 EVT MaskVT = Mask.getValueType(); 8635 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8636 "Incompatible types of Data and Mask"); 8637 if (IsCompressedMemory) { 8638 if (DataVT.isScalableVector()) 8639 report_fatal_error( 8640 "Cannot currently handle compressed memory with scalable vectors"); 8641 // Incrementing the pointer according to number of '1's in the mask. 8642 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8643 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8644 if (MaskIntVT.getSizeInBits() < 32) { 8645 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8646 MaskIntVT = MVT::i32; 8647 } 8648 8649 // Count '1's with POPCNT. 8650 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8651 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8652 // Scale is an element size in bytes. 8653 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8654 AddrVT); 8655 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8656 } else if (DataVT.isScalableVector()) { 8657 Increment = DAG.getVScale(DL, AddrVT, 8658 APInt(AddrVT.getFixedSizeInBits(), 8659 DataVT.getStoreSize().getKnownMinSize())); 8660 } else 8661 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8662 8663 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8664 } 8665 8666 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8667 EVT VecVT, const SDLoc &dl, 8668 ElementCount SubEC) { 8669 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8670 "Cannot index a scalable vector within a fixed-width vector"); 8671 8672 unsigned NElts = VecVT.getVectorMinNumElements(); 8673 unsigned NumSubElts = SubEC.getKnownMinValue(); 8674 EVT IdxVT = Idx.getValueType(); 8675 8676 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8677 // If this is a constant index and we know the value plus the number of the 8678 // elements in the subvector minus one is less than the minimum number of 8679 // elements then it's safe to return Idx. 8680 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8681 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8682 return Idx; 8683 SDValue VS = 8684 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8685 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8686 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8687 DAG.getConstant(NumSubElts, dl, IdxVT)); 8688 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8689 } 8690 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8691 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8692 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8693 DAG.getConstant(Imm, dl, IdxVT)); 8694 } 8695 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8696 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8697 DAG.getConstant(MaxIndex, dl, IdxVT)); 8698 } 8699 8700 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8701 SDValue VecPtr, EVT VecVT, 8702 SDValue Index) const { 8703 return getVectorSubVecPointer( 8704 DAG, VecPtr, VecVT, 8705 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8706 Index); 8707 } 8708 8709 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8710 SDValue VecPtr, EVT VecVT, 8711 EVT SubVecVT, 8712 SDValue Index) const { 8713 SDLoc dl(Index); 8714 // Make sure the index type is big enough to compute in. 8715 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8716 8717 EVT EltVT = VecVT.getVectorElementType(); 8718 8719 // Calculate the element offset and add it to the pointer. 8720 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8721 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8722 "Converting bits to bytes lost precision"); 8723 assert(SubVecVT.getVectorElementType() == EltVT && 8724 "Sub-vector must be a vector with matching element type"); 8725 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8726 SubVecVT.getVectorElementCount()); 8727 8728 EVT IdxVT = Index.getValueType(); 8729 if (SubVecVT.isScalableVector()) 8730 Index = 8731 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8732 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8733 8734 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8735 DAG.getConstant(EltSize, dl, IdxVT)); 8736 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8737 } 8738 8739 //===----------------------------------------------------------------------===// 8740 // Implementation of Emulated TLS Model 8741 //===----------------------------------------------------------------------===// 8742 8743 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8744 SelectionDAG &DAG) const { 8745 // Access to address of TLS varialbe xyz is lowered to a function call: 8746 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8747 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8748 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8749 SDLoc dl(GA); 8750 8751 ArgListTy Args; 8752 ArgListEntry Entry; 8753 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8754 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8755 StringRef EmuTlsVarName(NameString); 8756 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8757 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8758 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8759 Entry.Ty = VoidPtrType; 8760 Args.push_back(Entry); 8761 8762 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8763 8764 TargetLowering::CallLoweringInfo CLI(DAG); 8765 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8766 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8767 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8768 8769 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8770 // At last for X86 targets, maybe good for other targets too? 8771 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8772 MFI.setAdjustsStack(true); // Is this only for X86 target? 8773 MFI.setHasCalls(true); 8774 8775 assert((GA->getOffset() == 0) && 8776 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8777 return CallResult.first; 8778 } 8779 8780 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8781 SelectionDAG &DAG) const { 8782 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8783 if (!isCtlzFast()) 8784 return SDValue(); 8785 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8786 SDLoc dl(Op); 8787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8788 if (C->isZero() && CC == ISD::SETEQ) { 8789 EVT VT = Op.getOperand(0).getValueType(); 8790 SDValue Zext = Op.getOperand(0); 8791 if (VT.bitsLT(MVT::i32)) { 8792 VT = MVT::i32; 8793 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8794 } 8795 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8796 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8797 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8798 DAG.getConstant(Log2b, dl, MVT::i32)); 8799 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8800 } 8801 } 8802 return SDValue(); 8803 } 8804 8805 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8806 SDValue Op0 = Node->getOperand(0); 8807 SDValue Op1 = Node->getOperand(1); 8808 EVT VT = Op0.getValueType(); 8809 unsigned Opcode = Node->getOpcode(); 8810 SDLoc DL(Node); 8811 8812 // umin(x,y) -> sub(x,usubsat(x,y)) 8813 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8814 isOperationLegal(ISD::USUBSAT, VT)) { 8815 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8816 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8817 } 8818 8819 // umax(x,y) -> add(x,usubsat(y,x)) 8820 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8821 isOperationLegal(ISD::USUBSAT, VT)) { 8822 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8823 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8824 } 8825 8826 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8827 ISD::CondCode CC; 8828 switch (Opcode) { 8829 default: llvm_unreachable("How did we get here?"); 8830 case ISD::SMAX: CC = ISD::SETGT; break; 8831 case ISD::SMIN: CC = ISD::SETLT; break; 8832 case ISD::UMAX: CC = ISD::SETUGT; break; 8833 case ISD::UMIN: CC = ISD::SETULT; break; 8834 } 8835 8836 // FIXME: Should really try to split the vector in case it's legal on a 8837 // subvector. 8838 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8839 return DAG.UnrollVectorOp(Node); 8840 8841 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8842 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8843 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8844 } 8845 8846 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8847 unsigned Opcode = Node->getOpcode(); 8848 SDValue LHS = Node->getOperand(0); 8849 SDValue RHS = Node->getOperand(1); 8850 EVT VT = LHS.getValueType(); 8851 SDLoc dl(Node); 8852 8853 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8854 assert(VT.isInteger() && "Expected operands to be integers"); 8855 8856 // usub.sat(a, b) -> umax(a, b) - b 8857 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8858 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8859 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8860 } 8861 8862 // uadd.sat(a, b) -> umin(a, ~b) + b 8863 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8864 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8865 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8866 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8867 } 8868 8869 unsigned OverflowOp; 8870 switch (Opcode) { 8871 case ISD::SADDSAT: 8872 OverflowOp = ISD::SADDO; 8873 break; 8874 case ISD::UADDSAT: 8875 OverflowOp = ISD::UADDO; 8876 break; 8877 case ISD::SSUBSAT: 8878 OverflowOp = ISD::SSUBO; 8879 break; 8880 case ISD::USUBSAT: 8881 OverflowOp = ISD::USUBO; 8882 break; 8883 default: 8884 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8885 "addition or subtraction node."); 8886 } 8887 8888 // FIXME: Should really try to split the vector in case it's legal on a 8889 // subvector. 8890 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8891 return DAG.UnrollVectorOp(Node); 8892 8893 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8894 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8895 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8896 SDValue SumDiff = Result.getValue(0); 8897 SDValue Overflow = Result.getValue(1); 8898 SDValue Zero = DAG.getConstant(0, dl, VT); 8899 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8900 8901 if (Opcode == ISD::UADDSAT) { 8902 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8903 // (LHS + RHS) | OverflowMask 8904 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8905 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8906 } 8907 // Overflow ? 0xffff.... : (LHS + RHS) 8908 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8909 } 8910 8911 if (Opcode == ISD::USUBSAT) { 8912 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8913 // (LHS - RHS) & ~OverflowMask 8914 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8915 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8916 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8917 } 8918 // Overflow ? 0 : (LHS - RHS) 8919 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8920 } 8921 8922 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8923 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8924 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8925 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8926 DAG.getConstant(BitWidth - 1, dl, VT)); 8927 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8928 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8929 } 8930 8931 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8932 unsigned Opcode = Node->getOpcode(); 8933 bool IsSigned = Opcode == ISD::SSHLSAT; 8934 SDValue LHS = Node->getOperand(0); 8935 SDValue RHS = Node->getOperand(1); 8936 EVT VT = LHS.getValueType(); 8937 SDLoc dl(Node); 8938 8939 assert((Node->getOpcode() == ISD::SSHLSAT || 8940 Node->getOpcode() == ISD::USHLSAT) && 8941 "Expected a SHLSAT opcode"); 8942 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8943 assert(VT.isInteger() && "Expected operands to be integers"); 8944 8945 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8946 8947 unsigned BW = VT.getScalarSizeInBits(); 8948 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8949 SDValue Orig = 8950 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8951 8952 SDValue SatVal; 8953 if (IsSigned) { 8954 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8955 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8956 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8957 SatMin, SatMax, ISD::SETLT); 8958 } else { 8959 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8960 } 8961 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8962 8963 return Result; 8964 } 8965 8966 SDValue 8967 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8968 assert((Node->getOpcode() == ISD::SMULFIX || 8969 Node->getOpcode() == ISD::UMULFIX || 8970 Node->getOpcode() == ISD::SMULFIXSAT || 8971 Node->getOpcode() == ISD::UMULFIXSAT) && 8972 "Expected a fixed point multiplication opcode"); 8973 8974 SDLoc dl(Node); 8975 SDValue LHS = Node->getOperand(0); 8976 SDValue RHS = Node->getOperand(1); 8977 EVT VT = LHS.getValueType(); 8978 unsigned Scale = Node->getConstantOperandVal(2); 8979 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8980 Node->getOpcode() == ISD::UMULFIXSAT); 8981 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8982 Node->getOpcode() == ISD::SMULFIXSAT); 8983 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8984 unsigned VTSize = VT.getScalarSizeInBits(); 8985 8986 if (!Scale) { 8987 // [us]mul.fix(a, b, 0) -> mul(a, b) 8988 if (!Saturating) { 8989 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8990 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8991 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8992 SDValue Result = 8993 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8994 SDValue Product = Result.getValue(0); 8995 SDValue Overflow = Result.getValue(1); 8996 SDValue Zero = DAG.getConstant(0, dl, VT); 8997 8998 APInt MinVal = APInt::getSignedMinValue(VTSize); 8999 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 9000 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 9001 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 9002 // Xor the inputs, if resulting sign bit is 0 the product will be 9003 // positive, else negative. 9004 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 9005 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 9006 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 9007 return DAG.getSelect(dl, VT, Overflow, Result, Product); 9008 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 9009 SDValue Result = 9010 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 9011 SDValue Product = Result.getValue(0); 9012 SDValue Overflow = Result.getValue(1); 9013 9014 APInt MaxVal = APInt::getMaxValue(VTSize); 9015 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 9016 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 9017 } 9018 } 9019 9020 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 9021 "Expected scale to be less than the number of bits if signed or at " 9022 "most the number of bits if unsigned."); 9023 assert(LHS.getValueType() == RHS.getValueType() && 9024 "Expected both operands to be the same type"); 9025 9026 // Get the upper and lower bits of the result. 9027 SDValue Lo, Hi; 9028 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 9029 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 9030 if (isOperationLegalOrCustom(LoHiOp, VT)) { 9031 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 9032 Lo = Result.getValue(0); 9033 Hi = Result.getValue(1); 9034 } else if (isOperationLegalOrCustom(HiOp, VT)) { 9035 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9036 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 9037 } else if (VT.isVector()) { 9038 return SDValue(); 9039 } else { 9040 report_fatal_error("Unable to expand fixed point multiplication."); 9041 } 9042 9043 if (Scale == VTSize) 9044 // Result is just the top half since we'd be shifting by the width of the 9045 // operand. Overflow impossible so this works for both UMULFIX and 9046 // UMULFIXSAT. 9047 return Hi; 9048 9049 // The result will need to be shifted right by the scale since both operands 9050 // are scaled. The result is given to us in 2 halves, so we only want part of 9051 // both in the result. 9052 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9053 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 9054 DAG.getConstant(Scale, dl, ShiftTy)); 9055 if (!Saturating) 9056 return Result; 9057 9058 if (!Signed) { 9059 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 9060 // widened multiplication) aren't all zeroes. 9061 9062 // Saturate to max if ((Hi >> Scale) != 0), 9063 // which is the same as if (Hi > ((1 << Scale) - 1)) 9064 APInt MaxVal = APInt::getMaxValue(VTSize); 9065 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 9066 dl, VT); 9067 Result = DAG.getSelectCC(dl, Hi, LowMask, 9068 DAG.getConstant(MaxVal, dl, VT), Result, 9069 ISD::SETUGT); 9070 9071 return Result; 9072 } 9073 9074 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 9075 // widened multiplication) aren't all ones or all zeroes. 9076 9077 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 9078 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 9079 9080 if (Scale == 0) { 9081 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 9082 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 9083 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 9084 // Saturated to SatMin if wide product is negative, and SatMax if wide 9085 // product is positive ... 9086 SDValue Zero = DAG.getConstant(0, dl, VT); 9087 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 9088 ISD::SETLT); 9089 // ... but only if we overflowed. 9090 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 9091 } 9092 9093 // We handled Scale==0 above so all the bits to examine is in Hi. 9094 9095 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 9096 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 9097 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 9098 dl, VT); 9099 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 9100 // Saturate to min if (Hi >> (Scale - 1)) < -1), 9101 // which is the same as if (HI < (-1 << (Scale - 1)) 9102 SDValue HighMask = 9103 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 9104 dl, VT); 9105 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 9106 return Result; 9107 } 9108 9109 SDValue 9110 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 9111 SDValue LHS, SDValue RHS, 9112 unsigned Scale, SelectionDAG &DAG) const { 9113 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 9114 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 9115 "Expected a fixed point division opcode"); 9116 9117 EVT VT = LHS.getValueType(); 9118 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 9119 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 9120 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9121 9122 // If there is enough room in the type to upscale the LHS or downscale the 9123 // RHS before the division, we can perform it in this type without having to 9124 // resize. For signed operations, the LHS headroom is the number of 9125 // redundant sign bits, and for unsigned ones it is the number of zeroes. 9126 // The headroom for the RHS is the number of trailing zeroes. 9127 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 9128 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 9129 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 9130 9131 // For signed saturating operations, we need to be able to detect true integer 9132 // division overflow; that is, when you have MIN / -EPS. However, this 9133 // is undefined behavior and if we emit divisions that could take such 9134 // values it may cause undesired behavior (arithmetic exceptions on x86, for 9135 // example). 9136 // Avoid this by requiring an extra bit so that we never get this case. 9137 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 9138 // signed saturating division, we need to emit a whopping 32-bit division. 9139 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 9140 return SDValue(); 9141 9142 unsigned LHSShift = std::min(LHSLead, Scale); 9143 unsigned RHSShift = Scale - LHSShift; 9144 9145 // At this point, we know that if we shift the LHS up by LHSShift and the 9146 // RHS down by RHSShift, we can emit a regular division with a final scaling 9147 // factor of Scale. 9148 9149 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9150 if (LHSShift) 9151 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9152 DAG.getConstant(LHSShift, dl, ShiftTy)); 9153 if (RHSShift) 9154 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9155 DAG.getConstant(RHSShift, dl, ShiftTy)); 9156 9157 SDValue Quot; 9158 if (Signed) { 9159 // For signed operations, if the resulting quotient is negative and the 9160 // remainder is nonzero, subtract 1 from the quotient to round towards 9161 // negative infinity. 9162 SDValue Rem; 9163 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9164 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9165 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9166 if (isTypeLegal(VT) && 9167 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9168 Quot = DAG.getNode(ISD::SDIVREM, dl, 9169 DAG.getVTList(VT, VT), 9170 LHS, RHS); 9171 Rem = Quot.getValue(1); 9172 Quot = Quot.getValue(0); 9173 } else { 9174 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9175 LHS, RHS); 9176 Rem = DAG.getNode(ISD::SREM, dl, VT, 9177 LHS, RHS); 9178 } 9179 SDValue Zero = DAG.getConstant(0, dl, VT); 9180 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9181 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9182 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9183 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9184 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9185 DAG.getConstant(1, dl, VT)); 9186 Quot = DAG.getSelect(dl, VT, 9187 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9188 Sub1, Quot); 9189 } else 9190 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9191 LHS, RHS); 9192 9193 return Quot; 9194 } 9195 9196 void TargetLowering::expandUADDSUBO( 9197 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9198 SDLoc dl(Node); 9199 SDValue LHS = Node->getOperand(0); 9200 SDValue RHS = Node->getOperand(1); 9201 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9202 9203 // If ADD/SUBCARRY is legal, use that instead. 9204 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9205 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9206 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9207 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9208 { LHS, RHS, CarryIn }); 9209 Result = SDValue(NodeCarry.getNode(), 0); 9210 Overflow = SDValue(NodeCarry.getNode(), 1); 9211 return; 9212 } 9213 9214 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9215 LHS.getValueType(), LHS, RHS); 9216 9217 EVT ResultType = Node->getValueType(1); 9218 EVT SetCCType = getSetCCResultType( 9219 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9220 SDValue SetCC; 9221 if (IsAdd && isOneConstant(RHS)) { 9222 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9223 // the live range of X. We assume comparing with 0 is cheap. 9224 // The general case (X + C) < C is not necessarily beneficial. Although we 9225 // reduce the live range of X, we may introduce the materialization of 9226 // constant C. 9227 SetCC = 9228 DAG.getSetCC(dl, SetCCType, Result, 9229 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9230 } else { 9231 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9232 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9233 } 9234 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9235 } 9236 9237 void TargetLowering::expandSADDSUBO( 9238 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9239 SDLoc dl(Node); 9240 SDValue LHS = Node->getOperand(0); 9241 SDValue RHS = Node->getOperand(1); 9242 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9243 9244 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9245 LHS.getValueType(), LHS, RHS); 9246 9247 EVT ResultType = Node->getValueType(1); 9248 EVT OType = getSetCCResultType( 9249 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9250 9251 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9252 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9253 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9254 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9255 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9256 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9257 return; 9258 } 9259 9260 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9261 9262 // For an addition, the result should be less than one of the operands (LHS) 9263 // if and only if the other operand (RHS) is negative, otherwise there will 9264 // be overflow. 9265 // For a subtraction, the result should be less than one of the operands 9266 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9267 // otherwise there will be overflow. 9268 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9269 SDValue ConditionRHS = 9270 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9271 9272 Overflow = DAG.getBoolExtOrTrunc( 9273 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9274 ResultType, ResultType); 9275 } 9276 9277 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9278 SDValue &Overflow, SelectionDAG &DAG) const { 9279 SDLoc dl(Node); 9280 EVT VT = Node->getValueType(0); 9281 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9282 SDValue LHS = Node->getOperand(0); 9283 SDValue RHS = Node->getOperand(1); 9284 bool isSigned = Node->getOpcode() == ISD::SMULO; 9285 9286 // For power-of-two multiplications we can use a simpler shift expansion. 9287 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9288 const APInt &C = RHSC->getAPIntValue(); 9289 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9290 if (C.isPowerOf2()) { 9291 // smulo(x, signed_min) is same as umulo(x, signed_min). 9292 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9293 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9294 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9295 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9296 Overflow = DAG.getSetCC(dl, SetCCVT, 9297 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9298 dl, VT, Result, ShiftAmt), 9299 LHS, ISD::SETNE); 9300 return true; 9301 } 9302 } 9303 9304 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9305 if (VT.isVector()) 9306 WideVT = 9307 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9308 9309 SDValue BottomHalf; 9310 SDValue TopHalf; 9311 static const unsigned Ops[2][3] = 9312 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9313 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9314 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9315 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9316 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9317 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9318 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9319 RHS); 9320 TopHalf = BottomHalf.getValue(1); 9321 } else if (isTypeLegal(WideVT)) { 9322 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9323 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9324 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9325 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9326 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9327 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9328 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9329 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9330 } else { 9331 if (VT.isVector()) 9332 return false; 9333 9334 // We can fall back to a libcall with an illegal type for the MUL if we 9335 // have a libcall big enough. 9336 // Also, we can fall back to a division in some cases, but that's a big 9337 // performance hit in the general case. 9338 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9339 if (WideVT == MVT::i16) 9340 LC = RTLIB::MUL_I16; 9341 else if (WideVT == MVT::i32) 9342 LC = RTLIB::MUL_I32; 9343 else if (WideVT == MVT::i64) 9344 LC = RTLIB::MUL_I64; 9345 else if (WideVT == MVT::i128) 9346 LC = RTLIB::MUL_I128; 9347 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9348 9349 SDValue HiLHS; 9350 SDValue HiRHS; 9351 if (isSigned) { 9352 // The high part is obtained by SRA'ing all but one of the bits of low 9353 // part. 9354 unsigned LoSize = VT.getFixedSizeInBits(); 9355 HiLHS = 9356 DAG.getNode(ISD::SRA, dl, VT, LHS, 9357 DAG.getConstant(LoSize - 1, dl, 9358 getPointerTy(DAG.getDataLayout()))); 9359 HiRHS = 9360 DAG.getNode(ISD::SRA, dl, VT, RHS, 9361 DAG.getConstant(LoSize - 1, dl, 9362 getPointerTy(DAG.getDataLayout()))); 9363 } else { 9364 HiLHS = DAG.getConstant(0, dl, VT); 9365 HiRHS = DAG.getConstant(0, dl, VT); 9366 } 9367 9368 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9369 // pre-lowered to the correct types. This all depends upon WideVT not 9370 // being a legal type for the architecture and thus has to be split to 9371 // two arguments. 9372 SDValue Ret; 9373 TargetLowering::MakeLibCallOptions CallOptions; 9374 CallOptions.setSExt(isSigned); 9375 CallOptions.setIsPostTypeLegalization(true); 9376 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9377 // Halves of WideVT are packed into registers in different order 9378 // depending on platform endianness. This is usually handled by 9379 // the C calling convention, but we can't defer to it in 9380 // the legalizer. 9381 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9382 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9383 } else { 9384 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9385 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9386 } 9387 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9388 "Ret value is a collection of constituent nodes holding result."); 9389 if (DAG.getDataLayout().isLittleEndian()) { 9390 // Same as above. 9391 BottomHalf = Ret.getOperand(0); 9392 TopHalf = Ret.getOperand(1); 9393 } else { 9394 BottomHalf = Ret.getOperand(1); 9395 TopHalf = Ret.getOperand(0); 9396 } 9397 } 9398 9399 Result = BottomHalf; 9400 if (isSigned) { 9401 SDValue ShiftAmt = DAG.getConstant( 9402 VT.getScalarSizeInBits() - 1, dl, 9403 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9404 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9405 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9406 } else { 9407 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9408 DAG.getConstant(0, dl, VT), ISD::SETNE); 9409 } 9410 9411 // Truncate the result if SetCC returns a larger type than needed. 9412 EVT RType = Node->getValueType(1); 9413 if (RType.bitsLT(Overflow.getValueType())) 9414 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9415 9416 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9417 "Unexpected result type for S/UMULO legalization"); 9418 return true; 9419 } 9420 9421 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9422 SDLoc dl(Node); 9423 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9424 SDValue Op = Node->getOperand(0); 9425 EVT VT = Op.getValueType(); 9426 9427 if (VT.isScalableVector()) 9428 report_fatal_error( 9429 "Expanding reductions for scalable vectors is undefined."); 9430 9431 // Try to use a shuffle reduction for power of two vectors. 9432 if (VT.isPow2VectorType()) { 9433 while (VT.getVectorNumElements() > 1) { 9434 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9435 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9436 break; 9437 9438 SDValue Lo, Hi; 9439 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9440 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9441 VT = HalfVT; 9442 } 9443 } 9444 9445 EVT EltVT = VT.getVectorElementType(); 9446 unsigned NumElts = VT.getVectorNumElements(); 9447 9448 SmallVector<SDValue, 8> Ops; 9449 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9450 9451 SDValue Res = Ops[0]; 9452 for (unsigned i = 1; i < NumElts; i++) 9453 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9454 9455 // Result type may be wider than element type. 9456 if (EltVT != Node->getValueType(0)) 9457 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9458 return Res; 9459 } 9460 9461 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9462 SDLoc dl(Node); 9463 SDValue AccOp = Node->getOperand(0); 9464 SDValue VecOp = Node->getOperand(1); 9465 SDNodeFlags Flags = Node->getFlags(); 9466 9467 EVT VT = VecOp.getValueType(); 9468 EVT EltVT = VT.getVectorElementType(); 9469 9470 if (VT.isScalableVector()) 9471 report_fatal_error( 9472 "Expanding reductions for scalable vectors is undefined."); 9473 9474 unsigned NumElts = VT.getVectorNumElements(); 9475 9476 SmallVector<SDValue, 8> Ops; 9477 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9478 9479 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9480 9481 SDValue Res = AccOp; 9482 for (unsigned i = 0; i < NumElts; i++) 9483 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9484 9485 return Res; 9486 } 9487 9488 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9489 SelectionDAG &DAG) const { 9490 EVT VT = Node->getValueType(0); 9491 SDLoc dl(Node); 9492 bool isSigned = Node->getOpcode() == ISD::SREM; 9493 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9494 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9495 SDValue Dividend = Node->getOperand(0); 9496 SDValue Divisor = Node->getOperand(1); 9497 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9498 SDVTList VTs = DAG.getVTList(VT, VT); 9499 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9500 return true; 9501 } 9502 if (isOperationLegalOrCustom(DivOpc, VT)) { 9503 // X % Y -> X-X/Y*Y 9504 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9505 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9506 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9507 return true; 9508 } 9509 return false; 9510 } 9511 9512 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9513 SelectionDAG &DAG) const { 9514 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9515 SDLoc dl(SDValue(Node, 0)); 9516 SDValue Src = Node->getOperand(0); 9517 9518 // DstVT is the result type, while SatVT is the size to which we saturate 9519 EVT SrcVT = Src.getValueType(); 9520 EVT DstVT = Node->getValueType(0); 9521 9522 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9523 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9524 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9525 assert(SatWidth <= DstWidth && 9526 "Expected saturation width smaller than result width"); 9527 9528 // Determine minimum and maximum integer values and their corresponding 9529 // floating-point values. 9530 APInt MinInt, MaxInt; 9531 if (IsSigned) { 9532 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9533 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9534 } else { 9535 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9536 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9537 } 9538 9539 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9540 // libcall emission cannot handle this. Large result types will fail. 9541 if (SrcVT == MVT::f16) { 9542 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9543 SrcVT = Src.getValueType(); 9544 } 9545 9546 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9547 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9548 9549 APFloat::opStatus MinStatus = 9550 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9551 APFloat::opStatus MaxStatus = 9552 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9553 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9554 !(MaxStatus & APFloat::opStatus::opInexact); 9555 9556 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9557 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9558 9559 // If the integer bounds are exactly representable as floats and min/max are 9560 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9561 // of comparisons and selects. 9562 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9563 isOperationLegal(ISD::FMAXNUM, SrcVT); 9564 if (AreExactFloatBounds && MinMaxLegal) { 9565 SDValue Clamped = Src; 9566 9567 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9568 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9569 // Clamp by MaxFloat from above. NaN cannot occur. 9570 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9571 // Convert clamped value to integer. 9572 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9573 dl, DstVT, Clamped); 9574 9575 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9576 // which will cast to zero. 9577 if (!IsSigned) 9578 return FpToInt; 9579 9580 // Otherwise, select 0 if Src is NaN. 9581 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9582 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9583 ISD::CondCode::SETUO); 9584 } 9585 9586 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9587 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9588 9589 // Result of direct conversion. The assumption here is that the operation is 9590 // non-trapping and it's fine to apply it to an out-of-range value if we 9591 // select it away later. 9592 SDValue FpToInt = 9593 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9594 9595 SDValue Select = FpToInt; 9596 9597 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9598 // MinInt if Src is NaN. 9599 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9600 ISD::CondCode::SETULT); 9601 // If Src OGT MaxFloat, select MaxInt. 9602 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9603 ISD::CondCode::SETOGT); 9604 9605 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9606 // is already zero. 9607 if (!IsSigned) 9608 return Select; 9609 9610 // Otherwise, select 0 if Src is NaN. 9611 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9612 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9613 } 9614 9615 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9616 SelectionDAG &DAG) const { 9617 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9618 assert(Node->getValueType(0).isScalableVector() && 9619 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9620 9621 EVT VT = Node->getValueType(0); 9622 SDValue V1 = Node->getOperand(0); 9623 SDValue V2 = Node->getOperand(1); 9624 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9625 SDLoc DL(Node); 9626 9627 // Expand through memory thusly: 9628 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9629 // Store V1, Ptr 9630 // Store V2, Ptr + sizeof(V1) 9631 // If (Imm < 0) 9632 // TrailingElts = -Imm 9633 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9634 // else 9635 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9636 // Res = Load Ptr 9637 9638 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9639 9640 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9641 VT.getVectorElementCount() * 2); 9642 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9643 EVT PtrVT = StackPtr.getValueType(); 9644 auto &MF = DAG.getMachineFunction(); 9645 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9646 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9647 9648 // Store the lo part of CONCAT_VECTORS(V1, V2) 9649 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9650 // Store the hi part of CONCAT_VECTORS(V1, V2) 9651 SDValue OffsetToV2 = DAG.getVScale( 9652 DL, PtrVT, 9653 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9654 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9655 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9656 9657 if (Imm >= 0) { 9658 // Load back the required element. getVectorElementPointer takes care of 9659 // clamping the index if it's out-of-bounds. 9660 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9661 // Load the spliced result 9662 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9663 MachinePointerInfo::getUnknownStack(MF)); 9664 } 9665 9666 uint64_t TrailingElts = -Imm; 9667 9668 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9669 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9670 SDValue TrailingBytes = 9671 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9672 9673 if (TrailingElts > VT.getVectorMinNumElements()) { 9674 SDValue VLBytes = DAG.getVScale( 9675 DL, PtrVT, 9676 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9677 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9678 } 9679 9680 // Calculate the start address of the spliced result. 9681 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9682 9683 // Load the spliced result 9684 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9685 MachinePointerInfo::getUnknownStack(MF)); 9686 } 9687 9688 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9689 SDValue &LHS, SDValue &RHS, 9690 SDValue &CC, SDValue Mask, 9691 SDValue EVL, bool &NeedInvert, 9692 const SDLoc &dl, SDValue &Chain, 9693 bool IsSignaling) const { 9694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9695 MVT OpVT = LHS.getSimpleValueType(); 9696 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9697 NeedInvert = false; 9698 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9699 bool IsNonVP = !EVL; 9700 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9701 default: 9702 llvm_unreachable("Unknown condition code action!"); 9703 case TargetLowering::Legal: 9704 // Nothing to do. 9705 break; 9706 case TargetLowering::Expand: { 9707 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9708 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9709 std::swap(LHS, RHS); 9710 CC = DAG.getCondCode(InvCC); 9711 return true; 9712 } 9713 // Swapping operands didn't work. Try inverting the condition. 9714 bool NeedSwap = false; 9715 InvCC = getSetCCInverse(CCCode, OpVT); 9716 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9717 // If inverting the condition is not enough, try swapping operands 9718 // on top of it. 9719 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9720 NeedSwap = true; 9721 } 9722 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9723 CC = DAG.getCondCode(InvCC); 9724 NeedInvert = true; 9725 if (NeedSwap) 9726 std::swap(LHS, RHS); 9727 return true; 9728 } 9729 9730 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9731 unsigned Opc = 0; 9732 switch (CCCode) { 9733 default: 9734 llvm_unreachable("Don't know how to expand this condition!"); 9735 case ISD::SETUO: 9736 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9737 CC1 = ISD::SETUNE; 9738 CC2 = ISD::SETUNE; 9739 Opc = ISD::OR; 9740 break; 9741 } 9742 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9743 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9744 NeedInvert = true; 9745 LLVM_FALLTHROUGH; 9746 case ISD::SETO: 9747 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9748 "If SETO is expanded, SETOEQ must be legal!"); 9749 CC1 = ISD::SETOEQ; 9750 CC2 = ISD::SETOEQ; 9751 Opc = ISD::AND; 9752 break; 9753 case ISD::SETONE: 9754 case ISD::SETUEQ: 9755 // If the SETUO or SETO CC isn't legal, we might be able to use 9756 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9757 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9758 // the operands. 9759 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9760 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9761 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9762 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9763 CC1 = ISD::SETOGT; 9764 CC2 = ISD::SETOLT; 9765 Opc = ISD::OR; 9766 NeedInvert = ((unsigned)CCCode & 0x8U); 9767 break; 9768 } 9769 LLVM_FALLTHROUGH; 9770 case ISD::SETOEQ: 9771 case ISD::SETOGT: 9772 case ISD::SETOGE: 9773 case ISD::SETOLT: 9774 case ISD::SETOLE: 9775 case ISD::SETUNE: 9776 case ISD::SETUGT: 9777 case ISD::SETUGE: 9778 case ISD::SETULT: 9779 case ISD::SETULE: 9780 // If we are floating point, assign and break, otherwise fall through. 9781 if (!OpVT.isInteger()) { 9782 // We can use the 4th bit to tell if we are the unordered 9783 // or ordered version of the opcode. 9784 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9785 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9786 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9787 break; 9788 } 9789 // Fallthrough if we are unsigned integer. 9790 LLVM_FALLTHROUGH; 9791 case ISD::SETLE: 9792 case ISD::SETGT: 9793 case ISD::SETGE: 9794 case ISD::SETLT: 9795 case ISD::SETNE: 9796 case ISD::SETEQ: 9797 // If all combinations of inverting the condition and swapping operands 9798 // didn't work then we have no means to expand the condition. 9799 llvm_unreachable("Don't know how to expand this condition!"); 9800 } 9801 9802 SDValue SetCC1, SetCC2; 9803 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9804 // If we aren't the ordered or unorder operation, 9805 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9806 if (IsNonVP) { 9807 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9808 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9809 } else { 9810 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9811 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9812 } 9813 } else { 9814 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9815 if (IsNonVP) { 9816 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9817 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9818 } else { 9819 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9820 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9821 } 9822 } 9823 if (Chain) 9824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9825 SetCC2.getValue(1)); 9826 if (IsNonVP) 9827 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9828 else { 9829 // Transform the binary opcode to the VP equivalent. 9830 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9831 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9832 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9833 } 9834 RHS = SDValue(); 9835 CC = SDValue(); 9836 return true; 9837 } 9838 } 9839 return false; 9840 } 9841