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/MachineFrameInfo.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineJumpTableInfo.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/CodeGen/TargetRegisterInfo.h" 22 #include "llvm/CodeGen/TargetSubtargetInfo.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/ErrorHandling.h" 30 #include "llvm/Support/KnownBits.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Target/TargetLoweringObjectFile.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").getValueAsString() == "true") 57 return false; 58 59 // Conservatively require the attributes of the call to match those of 60 // the return. Ignore NoAlias and NonNull because they don't affect the 61 // call sequence. 62 AttributeList CallerAttrs = F.getAttributes(); 63 if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex) 64 .removeAttribute(Attribute::NoAlias) 65 .removeAttribute(Attribute::NonNull) 66 .hasAttributes()) 67 return false; 68 69 // It's not safe to eliminate the sign / zero extension of the return value. 70 if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) || 71 CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 72 return false; 73 74 // Check if the only use is a function return node. 75 return isUsedByReturnOnly(Node, Chain); 76 } 77 78 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 79 const uint32_t *CallerPreservedMask, 80 const SmallVectorImpl<CCValAssign> &ArgLocs, 81 const SmallVectorImpl<SDValue> &OutVals) const { 82 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 83 const CCValAssign &ArgLoc = ArgLocs[I]; 84 if (!ArgLoc.isRegLoc()) 85 continue; 86 MCRegister Reg = ArgLoc.getLocReg(); 87 // Only look at callee saved registers. 88 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 89 continue; 90 // Check that we pass the value used for the caller. 91 // (We look for a CopyFromReg reading a virtual register that is used 92 // for the function live-in value of register Reg) 93 SDValue Value = OutVals[I]; 94 if (Value->getOpcode() != ISD::CopyFromReg) 95 return false; 96 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 97 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 98 return false; 99 } 100 return true; 101 } 102 103 /// Set CallLoweringInfo attribute flags based on a call instruction 104 /// and called function attributes. 105 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 106 unsigned ArgIdx) { 107 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 108 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 109 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 110 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 111 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 112 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 113 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 114 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 115 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 116 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 117 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 118 Alignment = Call->getParamAlign(ArgIdx); 119 ByValType = nullptr; 120 if (IsByVal) 121 ByValType = Call->getParamByValType(ArgIdx); 122 PreallocatedType = nullptr; 123 if (IsPreallocated) 124 PreallocatedType = Call->getParamPreallocatedType(ArgIdx); 125 } 126 127 /// Generate a libcall taking the given operands as arguments and returning a 128 /// result of type RetVT. 129 std::pair<SDValue, SDValue> 130 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 131 ArrayRef<SDValue> Ops, 132 MakeLibCallOptions CallOptions, 133 const SDLoc &dl, 134 SDValue InChain) const { 135 if (!InChain) 136 InChain = DAG.getEntryNode(); 137 138 TargetLowering::ArgListTy Args; 139 Args.reserve(Ops.size()); 140 141 TargetLowering::ArgListEntry Entry; 142 for (unsigned i = 0; i < Ops.size(); ++i) { 143 SDValue NewOp = Ops[i]; 144 Entry.Node = NewOp; 145 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 146 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 147 CallOptions.IsSExt); 148 Entry.IsZExt = !Entry.IsSExt; 149 150 if (CallOptions.IsSoften && 151 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 152 Entry.IsSExt = Entry.IsZExt = false; 153 } 154 Args.push_back(Entry); 155 } 156 157 if (LC == RTLIB::UNKNOWN_LIBCALL) 158 report_fatal_error("Unsupported library call operation!"); 159 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 160 getPointerTy(DAG.getDataLayout())); 161 162 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 163 TargetLowering::CallLoweringInfo CLI(DAG); 164 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 165 bool zeroExtend = !signExtend; 166 167 if (CallOptions.IsSoften && 168 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 169 signExtend = zeroExtend = false; 170 } 171 172 CLI.setDebugLoc(dl) 173 .setChain(InChain) 174 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 175 .setNoReturn(CallOptions.DoesNotReturn) 176 .setDiscardResult(!CallOptions.IsReturnValueUsed) 177 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 178 .setSExtResult(signExtend) 179 .setZExtResult(zeroExtend); 180 return LowerCallTo(CLI); 181 } 182 183 bool TargetLowering::findOptimalMemOpLowering( 184 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 185 unsigned SrcAS, const AttributeList &FuncAttributes) const { 186 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 187 return false; 188 189 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 190 191 if (VT == MVT::Other) { 192 // Use the largest integer type whose alignment constraints are satisfied. 193 // We only need to check DstAlign here as SrcAlign is always greater or 194 // equal to DstAlign (or zero). 195 VT = MVT::i64; 196 if (Op.isFixedDstAlign()) 197 while ( 198 Op.getDstAlign() < (VT.getSizeInBits() / 8) && 199 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign().value())) 200 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 201 assert(VT.isInteger()); 202 203 // Find the largest legal integer type. 204 MVT LVT = MVT::i64; 205 while (!isTypeLegal(LVT)) 206 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 207 assert(LVT.isInteger()); 208 209 // If the type we've chosen is larger than the largest legal integer type 210 // then use that instead. 211 if (VT.bitsGT(LVT)) 212 VT = LVT; 213 } 214 215 unsigned NumMemOps = 0; 216 uint64_t Size = Op.size(); 217 while (Size) { 218 unsigned VTSize = VT.getSizeInBits() / 8; 219 while (VTSize > Size) { 220 // For now, only use non-vector load / store's for the left-over pieces. 221 EVT NewVT = VT; 222 unsigned NewVTSize; 223 224 bool Found = false; 225 if (VT.isVector() || VT.isFloatingPoint()) { 226 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 227 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 228 isSafeMemOpType(NewVT.getSimpleVT())) 229 Found = true; 230 else if (NewVT == MVT::i64 && 231 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 232 isSafeMemOpType(MVT::f64)) { 233 // i64 is usually not legal on 32-bit targets, but f64 may be. 234 NewVT = MVT::f64; 235 Found = true; 236 } 237 } 238 239 if (!Found) { 240 do { 241 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 242 if (NewVT == MVT::i8) 243 break; 244 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 245 } 246 NewVTSize = NewVT.getSizeInBits() / 8; 247 248 // If the new VT cannot cover all of the remaining bits, then consider 249 // issuing a (or a pair of) unaligned and overlapping load / store. 250 bool Fast; 251 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 252 allowsMisalignedMemoryAccesses( 253 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign().value() : 1, 254 MachineMemOperand::MONone, &Fast) && 255 Fast) 256 VTSize = Size; 257 else { 258 VT = NewVT; 259 VTSize = NewVTSize; 260 } 261 } 262 263 if (++NumMemOps > Limit) 264 return false; 265 266 MemOps.push_back(VT); 267 Size -= VTSize; 268 } 269 270 return true; 271 } 272 273 /// Soften the operands of a comparison. This code is shared among BR_CC, 274 /// SELECT_CC, and SETCC handlers. 275 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 276 SDValue &NewLHS, SDValue &NewRHS, 277 ISD::CondCode &CCCode, 278 const SDLoc &dl, const SDValue OldLHS, 279 const SDValue OldRHS) const { 280 SDValue Chain; 281 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 282 OldRHS, Chain); 283 } 284 285 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 286 SDValue &NewLHS, SDValue &NewRHS, 287 ISD::CondCode &CCCode, 288 const SDLoc &dl, const SDValue OldLHS, 289 const SDValue OldRHS, 290 SDValue &Chain, 291 bool IsSignaling) const { 292 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 293 // not supporting it. We can update this code when libgcc provides such 294 // functions. 295 296 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 297 && "Unsupported setcc type!"); 298 299 // Expand into one or more soft-fp libcall(s). 300 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 301 bool ShouldInvertCC = false; 302 switch (CCCode) { 303 case ISD::SETEQ: 304 case ISD::SETOEQ: 305 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 306 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 307 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 308 break; 309 case ISD::SETNE: 310 case ISD::SETUNE: 311 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 312 (VT == MVT::f64) ? RTLIB::UNE_F64 : 313 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 314 break; 315 case ISD::SETGE: 316 case ISD::SETOGE: 317 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 318 (VT == MVT::f64) ? RTLIB::OGE_F64 : 319 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 320 break; 321 case ISD::SETLT: 322 case ISD::SETOLT: 323 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 324 (VT == MVT::f64) ? RTLIB::OLT_F64 : 325 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 326 break; 327 case ISD::SETLE: 328 case ISD::SETOLE: 329 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 330 (VT == MVT::f64) ? RTLIB::OLE_F64 : 331 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 332 break; 333 case ISD::SETGT: 334 case ISD::SETOGT: 335 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 336 (VT == MVT::f64) ? RTLIB::OGT_F64 : 337 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 338 break; 339 case ISD::SETO: 340 ShouldInvertCC = true; 341 LLVM_FALLTHROUGH; 342 case ISD::SETUO: 343 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 344 (VT == MVT::f64) ? RTLIB::UO_F64 : 345 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 346 break; 347 case ISD::SETONE: 348 // SETONE = O && UNE 349 ShouldInvertCC = true; 350 LLVM_FALLTHROUGH; 351 case ISD::SETUEQ: 352 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 353 (VT == MVT::f64) ? RTLIB::UO_F64 : 354 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 355 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 356 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 357 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 358 break; 359 default: 360 // Invert CC for unordered comparisons 361 ShouldInvertCC = true; 362 switch (CCCode) { 363 case ISD::SETULT: 364 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 365 (VT == MVT::f64) ? RTLIB::OGE_F64 : 366 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 367 break; 368 case ISD::SETULE: 369 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 370 (VT == MVT::f64) ? RTLIB::OGT_F64 : 371 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 372 break; 373 case ISD::SETUGT: 374 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 375 (VT == MVT::f64) ? RTLIB::OLE_F64 : 376 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 377 break; 378 case ISD::SETUGE: 379 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 380 (VT == MVT::f64) ? RTLIB::OLT_F64 : 381 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 382 break; 383 default: llvm_unreachable("Do not know how to soften this setcc!"); 384 } 385 } 386 387 // Use the target specific return value for comparions lib calls. 388 EVT RetVT = getCmpLibcallReturnType(); 389 SDValue Ops[2] = {NewLHS, NewRHS}; 390 TargetLowering::MakeLibCallOptions CallOptions; 391 EVT OpsVT[2] = { OldLHS.getValueType(), 392 OldRHS.getValueType() }; 393 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 394 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 395 NewLHS = Call.first; 396 NewRHS = DAG.getConstant(0, dl, RetVT); 397 398 CCCode = getCmpLibcallCC(LC1); 399 if (ShouldInvertCC) { 400 assert(RetVT.isInteger()); 401 CCCode = getSetCCInverse(CCCode, RetVT); 402 } 403 404 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 405 // Update Chain. 406 Chain = Call.second; 407 } else { 408 EVT SetCCVT = 409 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 410 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 411 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 412 CCCode = getCmpLibcallCC(LC2); 413 if (ShouldInvertCC) 414 CCCode = getSetCCInverse(CCCode, RetVT); 415 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 416 if (Chain) 417 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 418 Call2.second); 419 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 420 Tmp.getValueType(), Tmp, NewLHS); 421 NewRHS = SDValue(); 422 } 423 } 424 425 /// Return the entry encoding for a jump table in the current function. The 426 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 427 unsigned TargetLowering::getJumpTableEncoding() const { 428 // In non-pic modes, just use the address of a block. 429 if (!isPositionIndependent()) 430 return MachineJumpTableInfo::EK_BlockAddress; 431 432 // In PIC mode, if the target supports a GPRel32 directive, use it. 433 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 434 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 435 436 // Otherwise, use a label difference. 437 return MachineJumpTableInfo::EK_LabelDifference32; 438 } 439 440 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 441 SelectionDAG &DAG) const { 442 // If our PIC model is GP relative, use the global offset table as the base. 443 unsigned JTEncoding = getJumpTableEncoding(); 444 445 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 446 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 447 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 448 449 return Table; 450 } 451 452 /// This returns the relocation base for the given PIC jumptable, the same as 453 /// getPICJumpTableRelocBase, but as an MCExpr. 454 const MCExpr * 455 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 456 unsigned JTI,MCContext &Ctx) const{ 457 // The normal PIC reloc base is the label at the start of the jump table. 458 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 459 } 460 461 bool 462 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 463 const TargetMachine &TM = getTargetMachine(); 464 const GlobalValue *GV = GA->getGlobal(); 465 466 // If the address is not even local to this DSO we will have to load it from 467 // a got and then add the offset. 468 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 469 return false; 470 471 // If the code is position independent we will have to add a base register. 472 if (isPositionIndependent()) 473 return false; 474 475 // Otherwise we can do it. 476 return true; 477 } 478 479 //===----------------------------------------------------------------------===// 480 // Optimization Methods 481 //===----------------------------------------------------------------------===// 482 483 /// If the specified instruction has a constant integer operand and there are 484 /// bits set in that constant that are not demanded, then clear those bits and 485 /// return true. 486 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 487 const APInt &DemandedBits, 488 const APInt &DemandedElts, 489 TargetLoweringOpt &TLO) const { 490 SDLoc DL(Op); 491 unsigned Opcode = Op.getOpcode(); 492 493 // Do target-specific constant optimization. 494 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 495 return TLO.New.getNode(); 496 497 // FIXME: ISD::SELECT, ISD::SELECT_CC 498 switch (Opcode) { 499 default: 500 break; 501 case ISD::XOR: 502 case ISD::AND: 503 case ISD::OR: { 504 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 505 if (!Op1C) 506 return false; 507 508 // If this is a 'not' op, don't touch it because that's a canonical form. 509 const APInt &C = Op1C->getAPIntValue(); 510 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 511 return false; 512 513 if (!C.isSubsetOf(DemandedBits)) { 514 EVT VT = Op.getValueType(); 515 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 516 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 517 return TLO.CombineTo(Op, NewOp); 518 } 519 520 break; 521 } 522 } 523 524 return false; 525 } 526 527 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 528 const APInt &DemandedBits, 529 TargetLoweringOpt &TLO) const { 530 EVT VT = Op.getValueType(); 531 APInt DemandedElts = VT.isVector() 532 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 533 : APInt(1, 1); 534 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 535 } 536 537 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 538 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 539 /// generalized for targets with other types of implicit widening casts. 540 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 541 const APInt &Demanded, 542 TargetLoweringOpt &TLO) const { 543 assert(Op.getNumOperands() == 2 && 544 "ShrinkDemandedOp only supports binary operators!"); 545 assert(Op.getNode()->getNumValues() == 1 && 546 "ShrinkDemandedOp only supports nodes with one result!"); 547 548 SelectionDAG &DAG = TLO.DAG; 549 SDLoc dl(Op); 550 551 // Early return, as this function cannot handle vector types. 552 if (Op.getValueType().isVector()) 553 return false; 554 555 // Don't do this if the node has another user, which may require the 556 // full value. 557 if (!Op.getNode()->hasOneUse()) 558 return false; 559 560 // Search for the smallest integer type with free casts to and from 561 // Op's type. For expedience, just check power-of-2 integer types. 562 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 563 unsigned DemandedSize = Demanded.getActiveBits(); 564 unsigned SmallVTBits = DemandedSize; 565 if (!isPowerOf2_32(SmallVTBits)) 566 SmallVTBits = NextPowerOf2(SmallVTBits); 567 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 568 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 569 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 570 TLI.isZExtFree(SmallVT, Op.getValueType())) { 571 // We found a type with free casts. 572 SDValue X = DAG.getNode( 573 Op.getOpcode(), dl, SmallVT, 574 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 575 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 576 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 577 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 578 return TLO.CombineTo(Op, Z); 579 } 580 } 581 return false; 582 } 583 584 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 585 DAGCombinerInfo &DCI) const { 586 SelectionDAG &DAG = DCI.DAG; 587 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 588 !DCI.isBeforeLegalizeOps()); 589 KnownBits Known; 590 591 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 592 if (Simplified) { 593 DCI.AddToWorklist(Op.getNode()); 594 DCI.CommitTargetLoweringOpt(TLO); 595 } 596 return Simplified; 597 } 598 599 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 600 KnownBits &Known, 601 TargetLoweringOpt &TLO, 602 unsigned Depth, 603 bool AssumeSingleUse) const { 604 EVT VT = Op.getValueType(); 605 606 // TODO: We can probably do more work on calculating the known bits and 607 // simplifying the operations for scalable vectors, but for now we just 608 // bail out. 609 if (VT.isScalableVector()) { 610 // Pretend we don't know anything for now. 611 Known = KnownBits(DemandedBits.getBitWidth()); 612 return false; 613 } 614 615 APInt DemandedElts = VT.isVector() 616 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 617 : APInt(1, 1); 618 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 619 AssumeSingleUse); 620 } 621 622 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 623 // TODO: Under what circumstances can we create nodes? Constant folding? 624 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 625 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 626 SelectionDAG &DAG, unsigned Depth) const { 627 // Limit search depth. 628 if (Depth >= SelectionDAG::MaxRecursionDepth) 629 return SDValue(); 630 631 // Ignore UNDEFs. 632 if (Op.isUndef()) 633 return SDValue(); 634 635 // Not demanding any bits/elts from Op. 636 if (DemandedBits == 0 || DemandedElts == 0) 637 return DAG.getUNDEF(Op.getValueType()); 638 639 unsigned NumElts = DemandedElts.getBitWidth(); 640 unsigned BitWidth = DemandedBits.getBitWidth(); 641 KnownBits LHSKnown, RHSKnown; 642 switch (Op.getOpcode()) { 643 case ISD::BITCAST: { 644 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 645 EVT SrcVT = Src.getValueType(); 646 EVT DstVT = Op.getValueType(); 647 if (SrcVT == DstVT) 648 return Src; 649 650 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 651 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 652 if (NumSrcEltBits == NumDstEltBits) 653 if (SDValue V = SimplifyMultipleUseDemandedBits( 654 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 655 return DAG.getBitcast(DstVT, V); 656 657 // TODO - bigendian once we have test coverage. 658 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 && 659 DAG.getDataLayout().isLittleEndian()) { 660 unsigned Scale = NumDstEltBits / NumSrcEltBits; 661 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 662 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 663 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 664 for (unsigned i = 0; i != Scale; ++i) { 665 unsigned Offset = i * NumSrcEltBits; 666 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 667 if (!Sub.isNullValue()) { 668 DemandedSrcBits |= Sub; 669 for (unsigned j = 0; j != NumElts; ++j) 670 if (DemandedElts[j]) 671 DemandedSrcElts.setBit((j * Scale) + i); 672 } 673 } 674 675 if (SDValue V = SimplifyMultipleUseDemandedBits( 676 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 677 return DAG.getBitcast(DstVT, V); 678 } 679 680 // TODO - bigendian once we have test coverage. 681 if ((NumSrcEltBits % NumDstEltBits) == 0 && 682 DAG.getDataLayout().isLittleEndian()) { 683 unsigned Scale = NumSrcEltBits / NumDstEltBits; 684 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 685 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 686 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 687 for (unsigned i = 0; i != NumElts; ++i) 688 if (DemandedElts[i]) { 689 unsigned Offset = (i % Scale) * NumDstEltBits; 690 DemandedSrcBits.insertBits(DemandedBits, Offset); 691 DemandedSrcElts.setBit(i / Scale); 692 } 693 694 if (SDValue V = SimplifyMultipleUseDemandedBits( 695 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 696 return DAG.getBitcast(DstVT, V); 697 } 698 699 break; 700 } 701 case ISD::AND: { 702 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 703 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 704 705 // If all of the demanded bits are known 1 on one side, return the other. 706 // These bits cannot contribute to the result of the 'and' in this 707 // context. 708 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 709 return Op.getOperand(0); 710 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 711 return Op.getOperand(1); 712 break; 713 } 714 case ISD::OR: { 715 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 716 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 717 718 // If all of the demanded bits are known zero on one side, return the 719 // other. These bits cannot contribute to the result of the 'or' in this 720 // context. 721 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 722 return Op.getOperand(0); 723 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 724 return Op.getOperand(1); 725 break; 726 } 727 case ISD::XOR: { 728 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 729 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 730 731 // If all of the demanded bits are known zero on one side, return the 732 // other. 733 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 734 return Op.getOperand(0); 735 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 736 return Op.getOperand(1); 737 break; 738 } 739 case ISD::SHL: { 740 // If we are only demanding sign bits then we can use the shift source 741 // directly. 742 if (const APInt *MaxSA = 743 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 744 SDValue Op0 = Op.getOperand(0); 745 unsigned ShAmt = MaxSA->getZExtValue(); 746 unsigned NumSignBits = 747 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 748 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 749 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 750 return Op0; 751 } 752 break; 753 } 754 case ISD::SETCC: { 755 SDValue Op0 = Op.getOperand(0); 756 SDValue Op1 = Op.getOperand(1); 757 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 758 // If (1) we only need the sign-bit, (2) the setcc operands are the same 759 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 760 // -1, we may be able to bypass the setcc. 761 if (DemandedBits.isSignMask() && 762 Op0.getScalarValueSizeInBits() == BitWidth && 763 getBooleanContents(Op0.getValueType()) == 764 BooleanContent::ZeroOrNegativeOneBooleanContent) { 765 // If we're testing X < 0, then this compare isn't needed - just use X! 766 // FIXME: We're limiting to integer types here, but this should also work 767 // if we don't care about FP signed-zero. The use of SETLT with FP means 768 // that we don't care about NaNs. 769 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 770 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 771 return Op0; 772 } 773 break; 774 } 775 case ISD::SIGN_EXTEND_INREG: { 776 // If none of the extended bits are demanded, eliminate the sextinreg. 777 SDValue Op0 = Op.getOperand(0); 778 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 779 unsigned ExBits = ExVT.getScalarSizeInBits(); 780 if (DemandedBits.getActiveBits() <= ExBits) 781 return Op0; 782 // If the input is already sign extended, just drop the extension. 783 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 784 if (NumSignBits >= (BitWidth - ExBits + 1)) 785 return Op0; 786 break; 787 } 788 case ISD::ANY_EXTEND_VECTOR_INREG: 789 case ISD::SIGN_EXTEND_VECTOR_INREG: 790 case ISD::ZERO_EXTEND_VECTOR_INREG: { 791 // If we only want the lowest element and none of extended bits, then we can 792 // return the bitcasted source vector. 793 SDValue Src = Op.getOperand(0); 794 EVT SrcVT = Src.getValueType(); 795 EVT DstVT = Op.getValueType(); 796 if (DemandedElts == 1 && DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 797 DAG.getDataLayout().isLittleEndian() && 798 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 799 return DAG.getBitcast(DstVT, Src); 800 } 801 break; 802 } 803 case ISD::INSERT_VECTOR_ELT: { 804 // If we don't demand the inserted element, return the base vector. 805 SDValue Vec = Op.getOperand(0); 806 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 807 EVT VecVT = Vec.getValueType(); 808 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 809 !DemandedElts[CIdx->getZExtValue()]) 810 return Vec; 811 break; 812 } 813 case ISD::INSERT_SUBVECTOR: { 814 // If we don't demand the inserted subvector, return the base vector. 815 SDValue Vec = Op.getOperand(0); 816 SDValue Sub = Op.getOperand(1); 817 uint64_t Idx = Op.getConstantOperandVal(2); 818 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 819 if (DemandedElts.extractBits(NumSubElts, Idx) == 0) 820 return Vec; 821 break; 822 } 823 case ISD::VECTOR_SHUFFLE: { 824 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 825 826 // If all the demanded elts are from one operand and are inline, 827 // then we can use the operand directly. 828 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 829 for (unsigned i = 0; i != NumElts; ++i) { 830 int M = ShuffleMask[i]; 831 if (M < 0 || !DemandedElts[i]) 832 continue; 833 AllUndef = false; 834 IdentityLHS &= (M == (int)i); 835 IdentityRHS &= ((M - NumElts) == i); 836 } 837 838 if (AllUndef) 839 return DAG.getUNDEF(Op.getValueType()); 840 if (IdentityLHS) 841 return Op.getOperand(0); 842 if (IdentityRHS) 843 return Op.getOperand(1); 844 break; 845 } 846 default: 847 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 848 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 849 Op, DemandedBits, DemandedElts, DAG, Depth)) 850 return V; 851 break; 852 } 853 return SDValue(); 854 } 855 856 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 857 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 858 unsigned Depth) const { 859 EVT VT = Op.getValueType(); 860 APInt DemandedElts = VT.isVector() 861 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 862 : APInt(1, 1); 863 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 864 Depth); 865 } 866 867 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 868 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 869 unsigned Depth) const { 870 APInt DemandedBits = APInt::getAllOnesValue(Op.getScalarValueSizeInBits()); 871 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 872 Depth); 873 } 874 875 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 876 /// result of Op are ever used downstream. If we can use this information to 877 /// simplify Op, create a new simplified DAG node and return true, returning the 878 /// original and new nodes in Old and New. Otherwise, analyze the expression and 879 /// return a mask of Known bits for the expression (used to simplify the 880 /// caller). The Known bits may only be accurate for those bits in the 881 /// OriginalDemandedBits and OriginalDemandedElts. 882 bool TargetLowering::SimplifyDemandedBits( 883 SDValue Op, const APInt &OriginalDemandedBits, 884 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 885 unsigned Depth, bool AssumeSingleUse) const { 886 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 887 assert(Op.getScalarValueSizeInBits() == BitWidth && 888 "Mask size mismatches value type size!"); 889 890 // Don't know anything. 891 Known = KnownBits(BitWidth); 892 893 // TODO: We can probably do more work on calculating the known bits and 894 // simplifying the operations for scalable vectors, but for now we just 895 // bail out. 896 if (Op.getValueType().isScalableVector()) 897 return false; 898 899 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 900 assert((!Op.getValueType().isVector() || 901 NumElts == Op.getValueType().getVectorNumElements()) && 902 "Unexpected vector size"); 903 904 APInt DemandedBits = OriginalDemandedBits; 905 APInt DemandedElts = OriginalDemandedElts; 906 SDLoc dl(Op); 907 auto &DL = TLO.DAG.getDataLayout(); 908 909 // Undef operand. 910 if (Op.isUndef()) 911 return false; 912 913 if (Op.getOpcode() == ISD::Constant) { 914 // We know all of the bits for a constant! 915 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 916 return false; 917 } 918 919 if (Op.getOpcode() == ISD::ConstantFP) { 920 // We know all of the bits for a floating point constant! 921 Known = KnownBits::makeConstant( 922 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 923 return false; 924 } 925 926 // Other users may use these bits. 927 EVT VT = Op.getValueType(); 928 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 929 if (Depth != 0) { 930 // If not at the root, Just compute the Known bits to 931 // simplify things downstream. 932 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 933 return false; 934 } 935 // If this is the root being simplified, allow it to have multiple uses, 936 // just set the DemandedBits/Elts to all bits. 937 DemandedBits = APInt::getAllOnesValue(BitWidth); 938 DemandedElts = APInt::getAllOnesValue(NumElts); 939 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 940 // Not demanding any bits/elts from Op. 941 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 942 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 943 // Limit search depth. 944 return false; 945 } 946 947 KnownBits Known2; 948 switch (Op.getOpcode()) { 949 case ISD::TargetConstant: 950 llvm_unreachable("Can't simplify this node"); 951 case ISD::SCALAR_TO_VECTOR: { 952 if (!DemandedElts[0]) 953 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 954 955 KnownBits SrcKnown; 956 SDValue Src = Op.getOperand(0); 957 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 958 APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth); 959 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 960 return true; 961 962 // Upper elements are undef, so only get the knownbits if we just demand 963 // the bottom element. 964 if (DemandedElts == 1) 965 Known = SrcKnown.anyextOrTrunc(BitWidth); 966 break; 967 } 968 case ISD::BUILD_VECTOR: 969 // Collect the known bits that are shared by every demanded element. 970 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 971 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 972 return false; // Don't fall through, will infinitely loop. 973 case ISD::LOAD: { 974 LoadSDNode *LD = cast<LoadSDNode>(Op); 975 if (getTargetConstantFromLoad(LD)) { 976 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 977 return false; // Don't fall through, will infinitely loop. 978 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 979 // If this is a ZEXTLoad and we are looking at the loaded value. 980 EVT MemVT = LD->getMemoryVT(); 981 unsigned MemBits = MemVT.getScalarSizeInBits(); 982 Known.Zero.setBitsFrom(MemBits); 983 return false; // Don't fall through, will infinitely loop. 984 } 985 break; 986 } 987 case ISD::INSERT_VECTOR_ELT: { 988 SDValue Vec = Op.getOperand(0); 989 SDValue Scl = Op.getOperand(1); 990 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 991 EVT VecVT = Vec.getValueType(); 992 993 // If index isn't constant, assume we need all vector elements AND the 994 // inserted element. 995 APInt DemandedVecElts(DemandedElts); 996 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 997 unsigned Idx = CIdx->getZExtValue(); 998 DemandedVecElts.clearBit(Idx); 999 1000 // Inserted element is not required. 1001 if (!DemandedElts[Idx]) 1002 return TLO.CombineTo(Op, Vec); 1003 } 1004 1005 KnownBits KnownScl; 1006 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1007 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1008 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1009 return true; 1010 1011 Known = KnownScl.anyextOrTrunc(BitWidth); 1012 1013 KnownBits KnownVec; 1014 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1015 Depth + 1)) 1016 return true; 1017 1018 if (!!DemandedVecElts) 1019 Known = KnownBits::commonBits(Known, KnownVec); 1020 1021 return false; 1022 } 1023 case ISD::INSERT_SUBVECTOR: { 1024 // Demand any elements from the subvector and the remainder from the src its 1025 // inserted into. 1026 SDValue Src = Op.getOperand(0); 1027 SDValue Sub = Op.getOperand(1); 1028 uint64_t Idx = Op.getConstantOperandVal(2); 1029 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1030 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1031 APInt DemandedSrcElts = DemandedElts; 1032 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 1033 1034 KnownBits KnownSub, KnownSrc; 1035 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1036 Depth + 1)) 1037 return true; 1038 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1039 Depth + 1)) 1040 return true; 1041 1042 Known.Zero.setAllBits(); 1043 Known.One.setAllBits(); 1044 if (!!DemandedSubElts) 1045 Known = KnownBits::commonBits(Known, KnownSub); 1046 if (!!DemandedSrcElts) 1047 Known = KnownBits::commonBits(Known, KnownSrc); 1048 1049 // Attempt to avoid multi-use src if we don't need anything from it. 1050 if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() || 1051 !DemandedSrcElts.isAllOnesValue()) { 1052 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1053 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1054 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1055 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1056 if (NewSub || NewSrc) { 1057 NewSub = NewSub ? NewSub : Sub; 1058 NewSrc = NewSrc ? NewSrc : Src; 1059 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1060 Op.getOperand(2)); 1061 return TLO.CombineTo(Op, NewOp); 1062 } 1063 } 1064 break; 1065 } 1066 case ISD::EXTRACT_SUBVECTOR: { 1067 // Offset the demanded elts by the subvector index. 1068 SDValue Src = Op.getOperand(0); 1069 if (Src.getValueType().isScalableVector()) 1070 break; 1071 uint64_t Idx = Op.getConstantOperandVal(1); 1072 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1073 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1074 1075 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1076 Depth + 1)) 1077 return true; 1078 1079 // Attempt to avoid multi-use src if we don't need anything from it. 1080 if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) { 1081 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1082 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1083 if (DemandedSrc) { 1084 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1085 Op.getOperand(1)); 1086 return TLO.CombineTo(Op, NewOp); 1087 } 1088 } 1089 break; 1090 } 1091 case ISD::CONCAT_VECTORS: { 1092 Known.Zero.setAllBits(); 1093 Known.One.setAllBits(); 1094 EVT SubVT = Op.getOperand(0).getValueType(); 1095 unsigned NumSubVecs = Op.getNumOperands(); 1096 unsigned NumSubElts = SubVT.getVectorNumElements(); 1097 for (unsigned i = 0; i != NumSubVecs; ++i) { 1098 APInt DemandedSubElts = 1099 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1100 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1101 Known2, TLO, Depth + 1)) 1102 return true; 1103 // Known bits are shared by every demanded subvector element. 1104 if (!!DemandedSubElts) 1105 Known = KnownBits::commonBits(Known, Known2); 1106 } 1107 break; 1108 } 1109 case ISD::VECTOR_SHUFFLE: { 1110 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1111 1112 // Collect demanded elements from shuffle operands.. 1113 APInt DemandedLHS(NumElts, 0); 1114 APInt DemandedRHS(NumElts, 0); 1115 for (unsigned i = 0; i != NumElts; ++i) { 1116 if (!DemandedElts[i]) 1117 continue; 1118 int M = ShuffleMask[i]; 1119 if (M < 0) { 1120 // For UNDEF elements, we don't know anything about the common state of 1121 // the shuffle result. 1122 DemandedLHS.clearAllBits(); 1123 DemandedRHS.clearAllBits(); 1124 break; 1125 } 1126 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1127 if (M < (int)NumElts) 1128 DemandedLHS.setBit(M); 1129 else 1130 DemandedRHS.setBit(M - NumElts); 1131 } 1132 1133 if (!!DemandedLHS || !!DemandedRHS) { 1134 SDValue Op0 = Op.getOperand(0); 1135 SDValue Op1 = Op.getOperand(1); 1136 1137 Known.Zero.setAllBits(); 1138 Known.One.setAllBits(); 1139 if (!!DemandedLHS) { 1140 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1141 Depth + 1)) 1142 return true; 1143 Known = KnownBits::commonBits(Known, Known2); 1144 } 1145 if (!!DemandedRHS) { 1146 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1147 Depth + 1)) 1148 return true; 1149 Known = KnownBits::commonBits(Known, Known2); 1150 } 1151 1152 // Attempt to avoid multi-use ops if we don't need anything from them. 1153 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1154 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1155 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1156 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1157 if (DemandedOp0 || DemandedOp1) { 1158 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1159 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1160 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1161 return TLO.CombineTo(Op, NewOp); 1162 } 1163 } 1164 break; 1165 } 1166 case ISD::AND: { 1167 SDValue Op0 = Op.getOperand(0); 1168 SDValue Op1 = Op.getOperand(1); 1169 1170 // If the RHS is a constant, check to see if the LHS would be zero without 1171 // using the bits from the RHS. Below, we use knowledge about the RHS to 1172 // simplify the LHS, here we're using information from the LHS to simplify 1173 // the RHS. 1174 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1175 // Do not increment Depth here; that can cause an infinite loop. 1176 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1177 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1178 if ((LHSKnown.Zero & DemandedBits) == 1179 (~RHSC->getAPIntValue() & DemandedBits)) 1180 return TLO.CombineTo(Op, Op0); 1181 1182 // If any of the set bits in the RHS are known zero on the LHS, shrink 1183 // the constant. 1184 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1185 DemandedElts, TLO)) 1186 return true; 1187 1188 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1189 // constant, but if this 'and' is only clearing bits that were just set by 1190 // the xor, then this 'and' can be eliminated by shrinking the mask of 1191 // the xor. For example, for a 32-bit X: 1192 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1193 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1194 LHSKnown.One == ~RHSC->getAPIntValue()) { 1195 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1196 return TLO.CombineTo(Op, Xor); 1197 } 1198 } 1199 1200 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1201 Depth + 1)) 1202 return true; 1203 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1204 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1205 Known2, TLO, Depth + 1)) 1206 return true; 1207 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1208 1209 // Attempt to avoid multi-use ops if we don't need anything from them. 1210 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1211 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1212 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1213 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1214 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1215 if (DemandedOp0 || DemandedOp1) { 1216 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1217 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1218 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1219 return TLO.CombineTo(Op, NewOp); 1220 } 1221 } 1222 1223 // If all of the demanded bits are known one on one side, return the other. 1224 // These bits cannot contribute to the result of the 'and'. 1225 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1226 return TLO.CombineTo(Op, Op0); 1227 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1228 return TLO.CombineTo(Op, Op1); 1229 // If all of the demanded bits in the inputs are known zeros, return zero. 1230 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1231 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1232 // If the RHS is a constant, see if we can simplify it. 1233 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1234 TLO)) 1235 return true; 1236 // If the operation can be done in a smaller type, do so. 1237 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1238 return true; 1239 1240 Known &= Known2; 1241 break; 1242 } 1243 case ISD::OR: { 1244 SDValue Op0 = Op.getOperand(0); 1245 SDValue Op1 = Op.getOperand(1); 1246 1247 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1248 Depth + 1)) 1249 return true; 1250 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1251 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1252 Known2, TLO, Depth + 1)) 1253 return true; 1254 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1255 1256 // Attempt to avoid multi-use ops if we don't need anything from them. 1257 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1258 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1259 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1260 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1261 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1262 if (DemandedOp0 || DemandedOp1) { 1263 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1264 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1265 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1266 return TLO.CombineTo(Op, NewOp); 1267 } 1268 } 1269 1270 // If all of the demanded bits are known zero on one side, return the other. 1271 // These bits cannot contribute to the result of the 'or'. 1272 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1273 return TLO.CombineTo(Op, Op0); 1274 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1275 return TLO.CombineTo(Op, Op1); 1276 // If the RHS is a constant, see if we can simplify it. 1277 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1278 return true; 1279 // If the operation can be done in a smaller type, do so. 1280 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1281 return true; 1282 1283 Known |= Known2; 1284 break; 1285 } 1286 case ISD::XOR: { 1287 SDValue Op0 = Op.getOperand(0); 1288 SDValue Op1 = Op.getOperand(1); 1289 1290 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1291 Depth + 1)) 1292 return true; 1293 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1294 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1295 Depth + 1)) 1296 return true; 1297 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1298 1299 // Attempt to avoid multi-use ops if we don't need anything from them. 1300 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1301 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1302 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1303 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1304 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1305 if (DemandedOp0 || DemandedOp1) { 1306 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1307 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1308 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1309 return TLO.CombineTo(Op, NewOp); 1310 } 1311 } 1312 1313 // If all of the demanded bits are known zero on one side, return the other. 1314 // These bits cannot contribute to the result of the 'xor'. 1315 if (DemandedBits.isSubsetOf(Known.Zero)) 1316 return TLO.CombineTo(Op, Op0); 1317 if (DemandedBits.isSubsetOf(Known2.Zero)) 1318 return TLO.CombineTo(Op, Op1); 1319 // If the operation can be done in a smaller type, do so. 1320 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1321 return true; 1322 1323 // If all of the unknown bits are known to be zero on one side or the other 1324 // turn this into an *inclusive* or. 1325 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1326 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1327 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1328 1329 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1330 if (C) { 1331 // If one side is a constant, and all of the set bits in the constant are 1332 // also known set on the other side, turn this into an AND, as we know 1333 // the bits will be cleared. 1334 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1335 // NB: it is okay if more bits are known than are requested 1336 if (C->getAPIntValue() == Known2.One) { 1337 SDValue ANDC = 1338 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1339 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1340 } 1341 1342 // If the RHS is a constant, see if we can change it. Don't alter a -1 1343 // constant because that's a 'not' op, and that is better for combining 1344 // and codegen. 1345 if (!C->isAllOnesValue() && 1346 DemandedBits.isSubsetOf(C->getAPIntValue())) { 1347 // We're flipping all demanded bits. Flip the undemanded bits too. 1348 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1349 return TLO.CombineTo(Op, New); 1350 } 1351 } 1352 1353 // If we can't turn this into a 'not', try to shrink the constant. 1354 if (!C || !C->isAllOnesValue()) 1355 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1356 return true; 1357 1358 Known ^= Known2; 1359 break; 1360 } 1361 case ISD::SELECT: 1362 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1363 Depth + 1)) 1364 return true; 1365 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1366 Depth + 1)) 1367 return true; 1368 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1369 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1370 1371 // If the operands are constants, see if we can simplify them. 1372 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1373 return true; 1374 1375 // Only known if known in both the LHS and RHS. 1376 Known = KnownBits::commonBits(Known, Known2); 1377 break; 1378 case ISD::SELECT_CC: 1379 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1380 Depth + 1)) 1381 return true; 1382 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1383 Depth + 1)) 1384 return true; 1385 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1386 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1387 1388 // If the operands are constants, see if we can simplify them. 1389 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1390 return true; 1391 1392 // Only known if known in both the LHS and RHS. 1393 Known = KnownBits::commonBits(Known, Known2); 1394 break; 1395 case ISD::SETCC: { 1396 SDValue Op0 = Op.getOperand(0); 1397 SDValue Op1 = Op.getOperand(1); 1398 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1399 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1400 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1401 // -1, we may be able to bypass the setcc. 1402 if (DemandedBits.isSignMask() && 1403 Op0.getScalarValueSizeInBits() == BitWidth && 1404 getBooleanContents(Op0.getValueType()) == 1405 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1406 // If we're testing X < 0, then this compare isn't needed - just use X! 1407 // FIXME: We're limiting to integer types here, but this should also work 1408 // if we don't care about FP signed-zero. The use of SETLT with FP means 1409 // that we don't care about NaNs. 1410 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1411 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1412 return TLO.CombineTo(Op, Op0); 1413 1414 // TODO: Should we check for other forms of sign-bit comparisons? 1415 // Examples: X <= -1, X >= 0 1416 } 1417 if (getBooleanContents(Op0.getValueType()) == 1418 TargetLowering::ZeroOrOneBooleanContent && 1419 BitWidth > 1) 1420 Known.Zero.setBitsFrom(1); 1421 break; 1422 } 1423 case ISD::SHL: { 1424 SDValue Op0 = Op.getOperand(0); 1425 SDValue Op1 = Op.getOperand(1); 1426 EVT ShiftVT = Op1.getValueType(); 1427 1428 if (const APInt *SA = 1429 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1430 unsigned ShAmt = SA->getZExtValue(); 1431 if (ShAmt == 0) 1432 return TLO.CombineTo(Op, Op0); 1433 1434 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1435 // single shift. We can do this if the bottom bits (which are shifted 1436 // out) are never demanded. 1437 // TODO - support non-uniform vector amounts. 1438 if (Op0.getOpcode() == ISD::SRL) { 1439 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1440 if (const APInt *SA2 = 1441 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1442 unsigned C1 = SA2->getZExtValue(); 1443 unsigned Opc = ISD::SHL; 1444 int Diff = ShAmt - C1; 1445 if (Diff < 0) { 1446 Diff = -Diff; 1447 Opc = ISD::SRL; 1448 } 1449 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1450 return TLO.CombineTo( 1451 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1452 } 1453 } 1454 } 1455 1456 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1457 // are not demanded. This will likely allow the anyext to be folded away. 1458 // TODO - support non-uniform vector amounts. 1459 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1460 SDValue InnerOp = Op0.getOperand(0); 1461 EVT InnerVT = InnerOp.getValueType(); 1462 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1463 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1464 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1465 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1466 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1467 ShTy = InnerVT; 1468 SDValue NarrowShl = 1469 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1470 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1471 return TLO.CombineTo( 1472 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1473 } 1474 1475 // Repeat the SHL optimization above in cases where an extension 1476 // intervenes: (shl (anyext (shr x, c1)), c2) to 1477 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1478 // aren't demanded (as above) and that the shifted upper c1 bits of 1479 // x aren't demanded. 1480 // TODO - support non-uniform vector amounts. 1481 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1482 InnerOp.hasOneUse()) { 1483 if (const APInt *SA2 = 1484 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1485 unsigned InnerShAmt = SA2->getZExtValue(); 1486 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1487 DemandedBits.getActiveBits() <= 1488 (InnerBits - InnerShAmt + ShAmt) && 1489 DemandedBits.countTrailingZeros() >= ShAmt) { 1490 SDValue NewSA = 1491 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1492 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1493 InnerOp.getOperand(0)); 1494 return TLO.CombineTo( 1495 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1496 } 1497 } 1498 } 1499 } 1500 1501 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1502 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1503 Depth + 1)) 1504 return true; 1505 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1506 Known.Zero <<= ShAmt; 1507 Known.One <<= ShAmt; 1508 // low bits known zero. 1509 Known.Zero.setLowBits(ShAmt); 1510 1511 // Try shrinking the operation as long as the shift amount will still be 1512 // in range. 1513 if ((ShAmt < DemandedBits.getActiveBits()) && 1514 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1515 return true; 1516 } 1517 1518 // If we are only demanding sign bits then we can use the shift source 1519 // directly. 1520 if (const APInt *MaxSA = 1521 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1522 unsigned ShAmt = MaxSA->getZExtValue(); 1523 unsigned NumSignBits = 1524 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1525 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1526 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1527 return TLO.CombineTo(Op, Op0); 1528 } 1529 break; 1530 } 1531 case ISD::SRL: { 1532 SDValue Op0 = Op.getOperand(0); 1533 SDValue Op1 = Op.getOperand(1); 1534 EVT ShiftVT = Op1.getValueType(); 1535 1536 if (const APInt *SA = 1537 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1538 unsigned ShAmt = SA->getZExtValue(); 1539 if (ShAmt == 0) 1540 return TLO.CombineTo(Op, Op0); 1541 1542 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1543 // single shift. We can do this if the top bits (which are shifted out) 1544 // are never demanded. 1545 // TODO - support non-uniform vector amounts. 1546 if (Op0.getOpcode() == ISD::SHL) { 1547 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1548 if (const APInt *SA2 = 1549 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1550 unsigned C1 = SA2->getZExtValue(); 1551 unsigned Opc = ISD::SRL; 1552 int Diff = ShAmt - C1; 1553 if (Diff < 0) { 1554 Diff = -Diff; 1555 Opc = ISD::SHL; 1556 } 1557 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1558 return TLO.CombineTo( 1559 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1560 } 1561 } 1562 } 1563 1564 APInt InDemandedMask = (DemandedBits << ShAmt); 1565 1566 // If the shift is exact, then it does demand the low bits (and knows that 1567 // they are zero). 1568 if (Op->getFlags().hasExact()) 1569 InDemandedMask.setLowBits(ShAmt); 1570 1571 // Compute the new bits that are at the top now. 1572 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1573 Depth + 1)) 1574 return true; 1575 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1576 Known.Zero.lshrInPlace(ShAmt); 1577 Known.One.lshrInPlace(ShAmt); 1578 // High bits known zero. 1579 Known.Zero.setHighBits(ShAmt); 1580 } 1581 break; 1582 } 1583 case ISD::SRA: { 1584 SDValue Op0 = Op.getOperand(0); 1585 SDValue Op1 = Op.getOperand(1); 1586 EVT ShiftVT = Op1.getValueType(); 1587 1588 // If we only want bits that already match the signbit then we don't need 1589 // to shift. 1590 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1591 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1592 NumHiDemandedBits) 1593 return TLO.CombineTo(Op, Op0); 1594 1595 // If this is an arithmetic shift right and only the low-bit is set, we can 1596 // always convert this into a logical shr, even if the shift amount is 1597 // variable. The low bit of the shift cannot be an input sign bit unless 1598 // the shift amount is >= the size of the datatype, which is undefined. 1599 if (DemandedBits.isOneValue()) 1600 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1601 1602 if (const APInt *SA = 1603 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1604 unsigned ShAmt = SA->getZExtValue(); 1605 if (ShAmt == 0) 1606 return TLO.CombineTo(Op, Op0); 1607 1608 APInt InDemandedMask = (DemandedBits << ShAmt); 1609 1610 // If the shift is exact, then it does demand the low bits (and knows that 1611 // they are zero). 1612 if (Op->getFlags().hasExact()) 1613 InDemandedMask.setLowBits(ShAmt); 1614 1615 // If any of the demanded bits are produced by the sign extension, we also 1616 // demand the input sign bit. 1617 if (DemandedBits.countLeadingZeros() < ShAmt) 1618 InDemandedMask.setSignBit(); 1619 1620 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1621 Depth + 1)) 1622 return true; 1623 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1624 Known.Zero.lshrInPlace(ShAmt); 1625 Known.One.lshrInPlace(ShAmt); 1626 1627 // If the input sign bit is known to be zero, or if none of the top bits 1628 // are demanded, turn this into an unsigned shift right. 1629 if (Known.Zero[BitWidth - ShAmt - 1] || 1630 DemandedBits.countLeadingZeros() >= ShAmt) { 1631 SDNodeFlags Flags; 1632 Flags.setExact(Op->getFlags().hasExact()); 1633 return TLO.CombineTo( 1634 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1635 } 1636 1637 int Log2 = DemandedBits.exactLogBase2(); 1638 if (Log2 >= 0) { 1639 // The bit must come from the sign. 1640 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1641 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1642 } 1643 1644 if (Known.One[BitWidth - ShAmt - 1]) 1645 // New bits are known one. 1646 Known.One.setHighBits(ShAmt); 1647 1648 // Attempt to avoid multi-use ops if we don't need anything from them. 1649 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1650 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1651 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1652 if (DemandedOp0) { 1653 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1654 return TLO.CombineTo(Op, NewOp); 1655 } 1656 } 1657 } 1658 break; 1659 } 1660 case ISD::FSHL: 1661 case ISD::FSHR: { 1662 SDValue Op0 = Op.getOperand(0); 1663 SDValue Op1 = Op.getOperand(1); 1664 SDValue Op2 = Op.getOperand(2); 1665 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1666 1667 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1668 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1669 1670 // For fshl, 0-shift returns the 1st arg. 1671 // For fshr, 0-shift returns the 2nd arg. 1672 if (Amt == 0) { 1673 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1674 Known, TLO, Depth + 1)) 1675 return true; 1676 break; 1677 } 1678 1679 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1680 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1681 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1682 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1683 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1684 Depth + 1)) 1685 return true; 1686 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1687 Depth + 1)) 1688 return true; 1689 1690 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1691 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1692 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1693 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1694 Known.One |= Known2.One; 1695 Known.Zero |= Known2.Zero; 1696 } 1697 1698 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1699 if (isPowerOf2_32(BitWidth)) { 1700 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1701 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1702 Known2, TLO, Depth + 1)) 1703 return true; 1704 } 1705 break; 1706 } 1707 case ISD::ROTL: 1708 case ISD::ROTR: { 1709 SDValue Op0 = Op.getOperand(0); 1710 SDValue Op1 = Op.getOperand(1); 1711 1712 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1713 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1714 return TLO.CombineTo(Op, Op0); 1715 1716 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1717 if (isPowerOf2_32(BitWidth)) { 1718 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1719 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1720 Depth + 1)) 1721 return true; 1722 } 1723 break; 1724 } 1725 case ISD::BITREVERSE: { 1726 SDValue Src = Op.getOperand(0); 1727 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1728 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1729 Depth + 1)) 1730 return true; 1731 Known.One = Known2.One.reverseBits(); 1732 Known.Zero = Known2.Zero.reverseBits(); 1733 break; 1734 } 1735 case ISD::BSWAP: { 1736 SDValue Src = Op.getOperand(0); 1737 APInt DemandedSrcBits = DemandedBits.byteSwap(); 1738 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1739 Depth + 1)) 1740 return true; 1741 Known.One = Known2.One.byteSwap(); 1742 Known.Zero = Known2.Zero.byteSwap(); 1743 break; 1744 } 1745 case ISD::CTPOP: { 1746 // If only 1 bit is demanded, replace with PARITY as long as we're before 1747 // op legalization. 1748 // FIXME: Limit to scalars for now. 1749 if (DemandedBits.isOneValue() && !TLO.LegalOps && !VT.isVector()) 1750 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 1751 Op.getOperand(0))); 1752 1753 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1754 break; 1755 } 1756 case ISD::SIGN_EXTEND_INREG: { 1757 SDValue Op0 = Op.getOperand(0); 1758 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1759 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 1760 1761 // If we only care about the highest bit, don't bother shifting right. 1762 if (DemandedBits.isSignMask()) { 1763 unsigned NumSignBits = 1764 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1765 bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1; 1766 // However if the input is already sign extended we expect the sign 1767 // extension to be dropped altogether later and do not simplify. 1768 if (!AlreadySignExtended) { 1769 // Compute the correct shift amount type, which must be getShiftAmountTy 1770 // for scalar types after legalization. 1771 EVT ShiftAmtTy = VT; 1772 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1773 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1774 1775 SDValue ShiftAmt = 1776 TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy); 1777 return TLO.CombineTo(Op, 1778 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 1779 } 1780 } 1781 1782 // If none of the extended bits are demanded, eliminate the sextinreg. 1783 if (DemandedBits.getActiveBits() <= ExVTBits) 1784 return TLO.CombineTo(Op, Op0); 1785 1786 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 1787 1788 // Since the sign extended bits are demanded, we know that the sign 1789 // bit is demanded. 1790 InputDemandedBits.setBit(ExVTBits - 1); 1791 1792 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 1793 return true; 1794 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1795 1796 // If the sign bit of the input is known set or clear, then we know the 1797 // top bits of the result. 1798 1799 // If the input sign bit is known zero, convert this into a zero extension. 1800 if (Known.Zero[ExVTBits - 1]) 1801 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 1802 1803 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 1804 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 1805 Known.One.setBitsFrom(ExVTBits); 1806 Known.Zero &= Mask; 1807 } else { // Input sign bit unknown 1808 Known.Zero &= Mask; 1809 Known.One &= Mask; 1810 } 1811 break; 1812 } 1813 case ISD::BUILD_PAIR: { 1814 EVT HalfVT = Op.getOperand(0).getValueType(); 1815 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1816 1817 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1818 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1819 1820 KnownBits KnownLo, KnownHi; 1821 1822 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 1823 return true; 1824 1825 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 1826 return true; 1827 1828 Known.Zero = KnownLo.Zero.zext(BitWidth) | 1829 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 1830 1831 Known.One = KnownLo.One.zext(BitWidth) | 1832 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 1833 break; 1834 } 1835 case ISD::ZERO_EXTEND: 1836 case ISD::ZERO_EXTEND_VECTOR_INREG: { 1837 SDValue Src = Op.getOperand(0); 1838 EVT SrcVT = Src.getValueType(); 1839 unsigned InBits = SrcVT.getScalarSizeInBits(); 1840 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1841 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 1842 1843 // If none of the top bits are demanded, convert this into an any_extend. 1844 if (DemandedBits.getActiveBits() <= InBits) { 1845 // If we only need the non-extended bits of the bottom element 1846 // then we can just bitcast to the result. 1847 if (IsVecInReg && DemandedElts == 1 && 1848 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1849 TLO.DAG.getDataLayout().isLittleEndian()) 1850 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1851 1852 unsigned Opc = 1853 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1854 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1855 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1856 } 1857 1858 APInt InDemandedBits = DemandedBits.trunc(InBits); 1859 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1860 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1861 Depth + 1)) 1862 return true; 1863 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1864 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1865 Known = Known.zext(BitWidth); 1866 1867 // Attempt to avoid multi-use ops if we don't need anything from them. 1868 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1869 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1870 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1871 break; 1872 } 1873 case ISD::SIGN_EXTEND: 1874 case ISD::SIGN_EXTEND_VECTOR_INREG: { 1875 SDValue Src = Op.getOperand(0); 1876 EVT SrcVT = Src.getValueType(); 1877 unsigned InBits = SrcVT.getScalarSizeInBits(); 1878 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1879 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 1880 1881 // If none of the top bits are demanded, convert this into an any_extend. 1882 if (DemandedBits.getActiveBits() <= InBits) { 1883 // If we only need the non-extended bits of the bottom element 1884 // then we can just bitcast to the result. 1885 if (IsVecInReg && DemandedElts == 1 && 1886 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1887 TLO.DAG.getDataLayout().isLittleEndian()) 1888 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1889 1890 unsigned Opc = 1891 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1892 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1893 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1894 } 1895 1896 APInt InDemandedBits = DemandedBits.trunc(InBits); 1897 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1898 1899 // Since some of the sign extended bits are demanded, we know that the sign 1900 // bit is demanded. 1901 InDemandedBits.setBit(InBits - 1); 1902 1903 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1904 Depth + 1)) 1905 return true; 1906 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1907 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1908 1909 // If the sign bit is known one, the top bits match. 1910 Known = Known.sext(BitWidth); 1911 1912 // If the sign bit is known zero, convert this to a zero extend. 1913 if (Known.isNonNegative()) { 1914 unsigned Opc = 1915 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 1916 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1917 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1918 } 1919 1920 // Attempt to avoid multi-use ops if we don't need anything from them. 1921 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1922 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1923 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1924 break; 1925 } 1926 case ISD::ANY_EXTEND: 1927 case ISD::ANY_EXTEND_VECTOR_INREG: { 1928 SDValue Src = Op.getOperand(0); 1929 EVT SrcVT = Src.getValueType(); 1930 unsigned InBits = SrcVT.getScalarSizeInBits(); 1931 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1932 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 1933 1934 // If we only need the bottom element then we can just bitcast. 1935 // TODO: Handle ANY_EXTEND? 1936 if (IsVecInReg && DemandedElts == 1 && 1937 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1938 TLO.DAG.getDataLayout().isLittleEndian()) 1939 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1940 1941 APInt InDemandedBits = DemandedBits.trunc(InBits); 1942 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1943 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1944 Depth + 1)) 1945 return true; 1946 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1947 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1948 Known = Known.anyext(BitWidth); 1949 1950 // Attempt to avoid multi-use ops if we don't need anything from them. 1951 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1952 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1953 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1954 break; 1955 } 1956 case ISD::TRUNCATE: { 1957 SDValue Src = Op.getOperand(0); 1958 1959 // Simplify the input, using demanded bit information, and compute the known 1960 // zero/one bits live out. 1961 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 1962 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 1963 if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1)) 1964 return true; 1965 Known = Known.trunc(BitWidth); 1966 1967 // Attempt to avoid multi-use ops if we don't need anything from them. 1968 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1969 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 1970 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 1971 1972 // If the input is only used by this truncate, see if we can shrink it based 1973 // on the known demanded bits. 1974 if (Src.getNode()->hasOneUse()) { 1975 switch (Src.getOpcode()) { 1976 default: 1977 break; 1978 case ISD::SRL: 1979 // Shrink SRL by a constant if none of the high bits shifted in are 1980 // demanded. 1981 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 1982 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 1983 // undesirable. 1984 break; 1985 1986 SDValue ShAmt = Src.getOperand(1); 1987 auto *ShAmtC = dyn_cast<ConstantSDNode>(ShAmt); 1988 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 1989 break; 1990 uint64_t ShVal = ShAmtC->getZExtValue(); 1991 1992 APInt HighBits = 1993 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 1994 HighBits.lshrInPlace(ShVal); 1995 HighBits = HighBits.trunc(BitWidth); 1996 1997 if (!(HighBits & DemandedBits)) { 1998 // None of the shifted in bits are needed. Add a truncate of the 1999 // shift input, then shift it. 2000 if (TLO.LegalTypes()) 2001 ShAmt = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL)); 2002 SDValue NewTrunc = 2003 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2004 return TLO.CombineTo( 2005 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, ShAmt)); 2006 } 2007 break; 2008 } 2009 } 2010 2011 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2012 break; 2013 } 2014 case ISD::AssertZext: { 2015 // AssertZext demands all of the high bits, plus any of the low bits 2016 // demanded by its users. 2017 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2018 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2019 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2020 TLO, Depth + 1)) 2021 return true; 2022 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2023 2024 Known.Zero |= ~InMask; 2025 break; 2026 } 2027 case ISD::EXTRACT_VECTOR_ELT: { 2028 SDValue Src = Op.getOperand(0); 2029 SDValue Idx = Op.getOperand(1); 2030 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2031 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2032 2033 if (SrcEltCnt.isScalable()) 2034 return false; 2035 2036 // Demand the bits from every vector element without a constant index. 2037 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2038 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 2039 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2040 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2041 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2042 2043 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2044 // anything about the extended bits. 2045 APInt DemandedSrcBits = DemandedBits; 2046 if (BitWidth > EltBitWidth) 2047 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2048 2049 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2050 Depth + 1)) 2051 return true; 2052 2053 // Attempt to avoid multi-use ops if we don't need anything from them. 2054 if (!DemandedSrcBits.isAllOnesValue() || 2055 !DemandedSrcElts.isAllOnesValue()) { 2056 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2057 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2058 SDValue NewOp = 2059 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2060 return TLO.CombineTo(Op, NewOp); 2061 } 2062 } 2063 2064 Known = Known2; 2065 if (BitWidth > EltBitWidth) 2066 Known = Known.anyext(BitWidth); 2067 break; 2068 } 2069 case ISD::BITCAST: { 2070 SDValue Src = Op.getOperand(0); 2071 EVT SrcVT = Src.getValueType(); 2072 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2073 2074 // If this is an FP->Int bitcast and if the sign bit is the only 2075 // thing demanded, turn this into a FGETSIGN. 2076 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2077 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2078 SrcVT.isFloatingPoint()) { 2079 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2080 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2081 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2082 SrcVT != MVT::f128) { 2083 // Cannot eliminate/lower SHL for f128 yet. 2084 EVT Ty = OpVTLegal ? VT : MVT::i32; 2085 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2086 // place. We expect the SHL to be eliminated by other optimizations. 2087 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2088 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2089 if (!OpVTLegal && OpVTSizeInBits > 32) 2090 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2091 unsigned ShVal = Op.getValueSizeInBits() - 1; 2092 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2093 return TLO.CombineTo(Op, 2094 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2095 } 2096 } 2097 2098 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2099 // Demand the elt/bit if any of the original elts/bits are demanded. 2100 // TODO - bigendian once we have test coverage. 2101 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0 && 2102 TLO.DAG.getDataLayout().isLittleEndian()) { 2103 unsigned Scale = BitWidth / NumSrcEltBits; 2104 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2105 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2106 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2107 for (unsigned i = 0; i != Scale; ++i) { 2108 unsigned Offset = i * NumSrcEltBits; 2109 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 2110 if (!Sub.isNullValue()) { 2111 DemandedSrcBits |= Sub; 2112 for (unsigned j = 0; j != NumElts; ++j) 2113 if (DemandedElts[j]) 2114 DemandedSrcElts.setBit((j * Scale) + i); 2115 } 2116 } 2117 2118 APInt KnownSrcUndef, KnownSrcZero; 2119 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2120 KnownSrcZero, TLO, Depth + 1)) 2121 return true; 2122 2123 KnownBits KnownSrcBits; 2124 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2125 KnownSrcBits, TLO, Depth + 1)) 2126 return true; 2127 } else if ((NumSrcEltBits % BitWidth) == 0 && 2128 TLO.DAG.getDataLayout().isLittleEndian()) { 2129 unsigned Scale = NumSrcEltBits / BitWidth; 2130 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2131 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2132 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2133 for (unsigned i = 0; i != NumElts; ++i) 2134 if (DemandedElts[i]) { 2135 unsigned Offset = (i % Scale) * BitWidth; 2136 DemandedSrcBits.insertBits(DemandedBits, Offset); 2137 DemandedSrcElts.setBit(i / Scale); 2138 } 2139 2140 if (SrcVT.isVector()) { 2141 APInt KnownSrcUndef, KnownSrcZero; 2142 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2143 KnownSrcZero, TLO, Depth + 1)) 2144 return true; 2145 } 2146 2147 KnownBits KnownSrcBits; 2148 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2149 KnownSrcBits, TLO, Depth + 1)) 2150 return true; 2151 } 2152 2153 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2154 // recursive call where Known may be useful to the caller. 2155 if (Depth > 0) { 2156 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2157 return false; 2158 } 2159 break; 2160 } 2161 case ISD::ADD: 2162 case ISD::MUL: 2163 case ISD::SUB: { 2164 // Add, Sub, and Mul don't demand any bits in positions beyond that 2165 // of the highest bit demanded of them. 2166 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2167 SDNodeFlags Flags = Op.getNode()->getFlags(); 2168 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2169 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2170 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2171 Depth + 1) || 2172 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2173 Depth + 1) || 2174 // See if the operation should be performed at a smaller bit width. 2175 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2176 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2177 // Disable the nsw and nuw flags. We can no longer guarantee that we 2178 // won't wrap after simplification. 2179 Flags.setNoSignedWrap(false); 2180 Flags.setNoUnsignedWrap(false); 2181 SDValue NewOp = 2182 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2183 return TLO.CombineTo(Op, NewOp); 2184 } 2185 return true; 2186 } 2187 2188 // Attempt to avoid multi-use ops if we don't need anything from them. 2189 if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 2190 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2191 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2192 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2193 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2194 if (DemandedOp0 || DemandedOp1) { 2195 Flags.setNoSignedWrap(false); 2196 Flags.setNoUnsignedWrap(false); 2197 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2198 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2199 SDValue NewOp = 2200 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2201 return TLO.CombineTo(Op, NewOp); 2202 } 2203 } 2204 2205 // If we have a constant operand, we may be able to turn it into -1 if we 2206 // do not demand the high bits. This can make the constant smaller to 2207 // encode, allow more general folding, or match specialized instruction 2208 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2209 // is probably not useful (and could be detrimental). 2210 ConstantSDNode *C = isConstOrConstSplat(Op1); 2211 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2212 if (C && !C->isAllOnesValue() && !C->isOne() && 2213 (C->getAPIntValue() | HighMask).isAllOnesValue()) { 2214 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2215 // Disable the nsw and nuw flags. We can no longer guarantee that we 2216 // won't wrap after simplification. 2217 Flags.setNoSignedWrap(false); 2218 Flags.setNoUnsignedWrap(false); 2219 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2220 return TLO.CombineTo(Op, NewOp); 2221 } 2222 2223 LLVM_FALLTHROUGH; 2224 } 2225 default: 2226 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2227 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2228 Known, TLO, Depth)) 2229 return true; 2230 break; 2231 } 2232 2233 // Just use computeKnownBits to compute output bits. 2234 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2235 break; 2236 } 2237 2238 // If we know the value of all of the demanded bits, return this as a 2239 // constant. 2240 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2241 // Avoid folding to a constant if any OpaqueConstant is involved. 2242 const SDNode *N = Op.getNode(); 2243 for (SDNodeIterator I = SDNodeIterator::begin(N), 2244 E = SDNodeIterator::end(N); 2245 I != E; ++I) { 2246 SDNode *Op = *I; 2247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2248 if (C->isOpaque()) 2249 return false; 2250 } 2251 if (VT.isInteger()) 2252 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2253 if (VT.isFloatingPoint()) 2254 return TLO.CombineTo( 2255 Op, 2256 TLO.DAG.getConstantFP( 2257 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2258 } 2259 2260 return false; 2261 } 2262 2263 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2264 const APInt &DemandedElts, 2265 APInt &KnownUndef, 2266 APInt &KnownZero, 2267 DAGCombinerInfo &DCI) const { 2268 SelectionDAG &DAG = DCI.DAG; 2269 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2270 !DCI.isBeforeLegalizeOps()); 2271 2272 bool Simplified = 2273 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2274 if (Simplified) { 2275 DCI.AddToWorklist(Op.getNode()); 2276 DCI.CommitTargetLoweringOpt(TLO); 2277 } 2278 2279 return Simplified; 2280 } 2281 2282 /// Given a vector binary operation and known undefined elements for each input 2283 /// operand, compute whether each element of the output is undefined. 2284 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2285 const APInt &UndefOp0, 2286 const APInt &UndefOp1) { 2287 EVT VT = BO.getValueType(); 2288 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2289 "Vector binop only"); 2290 2291 EVT EltVT = VT.getVectorElementType(); 2292 unsigned NumElts = VT.getVectorNumElements(); 2293 assert(UndefOp0.getBitWidth() == NumElts && 2294 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2295 2296 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2297 const APInt &UndefVals) { 2298 if (UndefVals[Index]) 2299 return DAG.getUNDEF(EltVT); 2300 2301 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2302 // Try hard to make sure that the getNode() call is not creating temporary 2303 // nodes. Ignore opaque integers because they do not constant fold. 2304 SDValue Elt = BV->getOperand(Index); 2305 auto *C = dyn_cast<ConstantSDNode>(Elt); 2306 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2307 return Elt; 2308 } 2309 2310 return SDValue(); 2311 }; 2312 2313 APInt KnownUndef = APInt::getNullValue(NumElts); 2314 for (unsigned i = 0; i != NumElts; ++i) { 2315 // If both inputs for this element are either constant or undef and match 2316 // the element type, compute the constant/undef result for this element of 2317 // the vector. 2318 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2319 // not handle FP constants. The code within getNode() should be refactored 2320 // to avoid the danger of creating a bogus temporary node here. 2321 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2322 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2323 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2324 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2325 KnownUndef.setBit(i); 2326 } 2327 return KnownUndef; 2328 } 2329 2330 bool TargetLowering::SimplifyDemandedVectorElts( 2331 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2332 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2333 bool AssumeSingleUse) const { 2334 EVT VT = Op.getValueType(); 2335 unsigned Opcode = Op.getOpcode(); 2336 APInt DemandedElts = OriginalDemandedElts; 2337 unsigned NumElts = DemandedElts.getBitWidth(); 2338 assert(VT.isVector() && "Expected vector op"); 2339 2340 KnownUndef = KnownZero = APInt::getNullValue(NumElts); 2341 2342 // TODO: For now we assume we know nothing about scalable vectors. 2343 if (VT.isScalableVector()) 2344 return false; 2345 2346 assert(VT.getVectorNumElements() == NumElts && 2347 "Mask size mismatches value type element count!"); 2348 2349 // Undef operand. 2350 if (Op.isUndef()) { 2351 KnownUndef.setAllBits(); 2352 return false; 2353 } 2354 2355 // If Op has other users, assume that all elements are needed. 2356 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2357 DemandedElts.setAllBits(); 2358 2359 // Not demanding any elements from Op. 2360 if (DemandedElts == 0) { 2361 KnownUndef.setAllBits(); 2362 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2363 } 2364 2365 // Limit search depth. 2366 if (Depth >= SelectionDAG::MaxRecursionDepth) 2367 return false; 2368 2369 SDLoc DL(Op); 2370 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2371 2372 // Helper for demanding the specified elements and all the bits of both binary 2373 // operands. 2374 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2375 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2376 TLO.DAG, Depth + 1); 2377 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2378 TLO.DAG, Depth + 1); 2379 if (NewOp0 || NewOp1) { 2380 SDValue NewOp = TLO.DAG.getNode( 2381 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2382 return TLO.CombineTo(Op, NewOp); 2383 } 2384 return false; 2385 }; 2386 2387 switch (Opcode) { 2388 case ISD::SCALAR_TO_VECTOR: { 2389 if (!DemandedElts[0]) { 2390 KnownUndef.setAllBits(); 2391 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2392 } 2393 KnownUndef.setHighBits(NumElts - 1); 2394 break; 2395 } 2396 case ISD::BITCAST: { 2397 SDValue Src = Op.getOperand(0); 2398 EVT SrcVT = Src.getValueType(); 2399 2400 // We only handle vectors here. 2401 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2402 if (!SrcVT.isVector()) 2403 break; 2404 2405 // Fast handling of 'identity' bitcasts. 2406 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2407 if (NumSrcElts == NumElts) 2408 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2409 KnownZero, TLO, Depth + 1); 2410 2411 APInt SrcZero, SrcUndef; 2412 APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts); 2413 2414 // Bitcast from 'large element' src vector to 'small element' vector, we 2415 // must demand a source element if any DemandedElt maps to it. 2416 if ((NumElts % NumSrcElts) == 0) { 2417 unsigned Scale = NumElts / NumSrcElts; 2418 for (unsigned i = 0; i != NumElts; ++i) 2419 if (DemandedElts[i]) 2420 SrcDemandedElts.setBit(i / Scale); 2421 2422 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2423 TLO, Depth + 1)) 2424 return true; 2425 2426 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2427 // of the large element. 2428 // TODO - bigendian once we have test coverage. 2429 if (TLO.DAG.getDataLayout().isLittleEndian()) { 2430 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2431 APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits); 2432 for (unsigned i = 0; i != NumElts; ++i) 2433 if (DemandedElts[i]) { 2434 unsigned Ofs = (i % Scale) * EltSizeInBits; 2435 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2436 } 2437 2438 KnownBits Known; 2439 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2440 TLO, Depth + 1)) 2441 return true; 2442 } 2443 2444 // If the src element is zero/undef then all the output elements will be - 2445 // only demanded elements are guaranteed to be correct. 2446 for (unsigned i = 0; i != NumSrcElts; ++i) { 2447 if (SrcDemandedElts[i]) { 2448 if (SrcZero[i]) 2449 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2450 if (SrcUndef[i]) 2451 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2452 } 2453 } 2454 } 2455 2456 // Bitcast from 'small element' src vector to 'large element' vector, we 2457 // demand all smaller source elements covered by the larger demanded element 2458 // of this vector. 2459 if ((NumSrcElts % NumElts) == 0) { 2460 unsigned Scale = NumSrcElts / NumElts; 2461 for (unsigned i = 0; i != NumElts; ++i) 2462 if (DemandedElts[i]) 2463 SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale); 2464 2465 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2466 TLO, Depth + 1)) 2467 return true; 2468 2469 // If all the src elements covering an output element are zero/undef, then 2470 // the output element will be as well, assuming it was demanded. 2471 for (unsigned i = 0; i != NumElts; ++i) { 2472 if (DemandedElts[i]) { 2473 if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue()) 2474 KnownZero.setBit(i); 2475 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue()) 2476 KnownUndef.setBit(i); 2477 } 2478 } 2479 } 2480 break; 2481 } 2482 case ISD::BUILD_VECTOR: { 2483 // Check all elements and simplify any unused elements with UNDEF. 2484 if (!DemandedElts.isAllOnesValue()) { 2485 // Don't simplify BROADCASTS. 2486 if (llvm::any_of(Op->op_values(), 2487 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2488 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2489 bool Updated = false; 2490 for (unsigned i = 0; i != NumElts; ++i) { 2491 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2492 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2493 KnownUndef.setBit(i); 2494 Updated = true; 2495 } 2496 } 2497 if (Updated) 2498 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2499 } 2500 } 2501 for (unsigned i = 0; i != NumElts; ++i) { 2502 SDValue SrcOp = Op.getOperand(i); 2503 if (SrcOp.isUndef()) { 2504 KnownUndef.setBit(i); 2505 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2506 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2507 KnownZero.setBit(i); 2508 } 2509 } 2510 break; 2511 } 2512 case ISD::CONCAT_VECTORS: { 2513 EVT SubVT = Op.getOperand(0).getValueType(); 2514 unsigned NumSubVecs = Op.getNumOperands(); 2515 unsigned NumSubElts = SubVT.getVectorNumElements(); 2516 for (unsigned i = 0; i != NumSubVecs; ++i) { 2517 SDValue SubOp = Op.getOperand(i); 2518 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2519 APInt SubUndef, SubZero; 2520 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2521 Depth + 1)) 2522 return true; 2523 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2524 KnownZero.insertBits(SubZero, i * NumSubElts); 2525 } 2526 break; 2527 } 2528 case ISD::INSERT_SUBVECTOR: { 2529 // Demand any elements from the subvector and the remainder from the src its 2530 // inserted into. 2531 SDValue Src = Op.getOperand(0); 2532 SDValue Sub = Op.getOperand(1); 2533 uint64_t Idx = Op.getConstantOperandVal(2); 2534 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2535 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2536 APInt DemandedSrcElts = DemandedElts; 2537 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2538 2539 APInt SubUndef, SubZero; 2540 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2541 Depth + 1)) 2542 return true; 2543 2544 // If none of the src operand elements are demanded, replace it with undef. 2545 if (!DemandedSrcElts && !Src.isUndef()) 2546 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2547 TLO.DAG.getUNDEF(VT), Sub, 2548 Op.getOperand(2))); 2549 2550 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2551 TLO, Depth + 1)) 2552 return true; 2553 KnownUndef.insertBits(SubUndef, Idx); 2554 KnownZero.insertBits(SubZero, Idx); 2555 2556 // Attempt to avoid multi-use ops if we don't need anything from them. 2557 if (!DemandedSrcElts.isAllOnesValue() || 2558 !DemandedSubElts.isAllOnesValue()) { 2559 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2560 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2561 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2562 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2563 if (NewSrc || NewSub) { 2564 NewSrc = NewSrc ? NewSrc : Src; 2565 NewSub = NewSub ? NewSub : Sub; 2566 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2567 NewSub, Op.getOperand(2)); 2568 return TLO.CombineTo(Op, NewOp); 2569 } 2570 } 2571 break; 2572 } 2573 case ISD::EXTRACT_SUBVECTOR: { 2574 // Offset the demanded elts by the subvector index. 2575 SDValue Src = Op.getOperand(0); 2576 if (Src.getValueType().isScalableVector()) 2577 break; 2578 uint64_t Idx = Op.getConstantOperandVal(1); 2579 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2580 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2581 2582 APInt SrcUndef, SrcZero; 2583 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2584 Depth + 1)) 2585 return true; 2586 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2587 KnownZero = SrcZero.extractBits(NumElts, Idx); 2588 2589 // Attempt to avoid multi-use ops if we don't need anything from them. 2590 if (!DemandedElts.isAllOnesValue()) { 2591 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2592 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2593 if (NewSrc) { 2594 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2595 Op.getOperand(1)); 2596 return TLO.CombineTo(Op, NewOp); 2597 } 2598 } 2599 break; 2600 } 2601 case ISD::INSERT_VECTOR_ELT: { 2602 SDValue Vec = Op.getOperand(0); 2603 SDValue Scl = Op.getOperand(1); 2604 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2605 2606 // For a legal, constant insertion index, if we don't need this insertion 2607 // then strip it, else remove it from the demanded elts. 2608 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2609 unsigned Idx = CIdx->getZExtValue(); 2610 if (!DemandedElts[Idx]) 2611 return TLO.CombineTo(Op, Vec); 2612 2613 APInt DemandedVecElts(DemandedElts); 2614 DemandedVecElts.clearBit(Idx); 2615 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2616 KnownZero, TLO, Depth + 1)) 2617 return true; 2618 2619 KnownUndef.setBitVal(Idx, Scl.isUndef()); 2620 2621 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 2622 break; 2623 } 2624 2625 APInt VecUndef, VecZero; 2626 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2627 Depth + 1)) 2628 return true; 2629 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2630 break; 2631 } 2632 case ISD::VSELECT: { 2633 // Try to transform the select condition based on the current demanded 2634 // elements. 2635 // TODO: If a condition element is undef, we can choose from one arm of the 2636 // select (and if one arm is undef, then we can propagate that to the 2637 // result). 2638 // TODO - add support for constant vselect masks (see IR version of this). 2639 APInt UnusedUndef, UnusedZero; 2640 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 2641 UnusedZero, TLO, Depth + 1)) 2642 return true; 2643 2644 // See if we can simplify either vselect operand. 2645 APInt DemandedLHS(DemandedElts); 2646 APInt DemandedRHS(DemandedElts); 2647 APInt UndefLHS, ZeroLHS; 2648 APInt UndefRHS, ZeroRHS; 2649 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 2650 ZeroLHS, TLO, Depth + 1)) 2651 return true; 2652 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 2653 ZeroRHS, TLO, Depth + 1)) 2654 return true; 2655 2656 KnownUndef = UndefLHS & UndefRHS; 2657 KnownZero = ZeroLHS & ZeroRHS; 2658 break; 2659 } 2660 case ISD::VECTOR_SHUFFLE: { 2661 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 2662 2663 // Collect demanded elements from shuffle operands.. 2664 APInt DemandedLHS(NumElts, 0); 2665 APInt DemandedRHS(NumElts, 0); 2666 for (unsigned i = 0; i != NumElts; ++i) { 2667 int M = ShuffleMask[i]; 2668 if (M < 0 || !DemandedElts[i]) 2669 continue; 2670 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 2671 if (M < (int)NumElts) 2672 DemandedLHS.setBit(M); 2673 else 2674 DemandedRHS.setBit(M - NumElts); 2675 } 2676 2677 // See if we can simplify either shuffle operand. 2678 APInt UndefLHS, ZeroLHS; 2679 APInt UndefRHS, ZeroRHS; 2680 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 2681 ZeroLHS, TLO, Depth + 1)) 2682 return true; 2683 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 2684 ZeroRHS, TLO, Depth + 1)) 2685 return true; 2686 2687 // Simplify mask using undef elements from LHS/RHS. 2688 bool Updated = false; 2689 bool IdentityLHS = true, IdentityRHS = true; 2690 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 2691 for (unsigned i = 0; i != NumElts; ++i) { 2692 int &M = NewMask[i]; 2693 if (M < 0) 2694 continue; 2695 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 2696 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 2697 Updated = true; 2698 M = -1; 2699 } 2700 IdentityLHS &= (M < 0) || (M == (int)i); 2701 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 2702 } 2703 2704 // Update legal shuffle masks based on demanded elements if it won't reduce 2705 // to Identity which can cause premature removal of the shuffle mask. 2706 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 2707 SDValue LegalShuffle = 2708 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 2709 NewMask, TLO.DAG); 2710 if (LegalShuffle) 2711 return TLO.CombineTo(Op, LegalShuffle); 2712 } 2713 2714 // Propagate undef/zero elements from LHS/RHS. 2715 for (unsigned i = 0; i != NumElts; ++i) { 2716 int M = ShuffleMask[i]; 2717 if (M < 0) { 2718 KnownUndef.setBit(i); 2719 } else if (M < (int)NumElts) { 2720 if (UndefLHS[M]) 2721 KnownUndef.setBit(i); 2722 if (ZeroLHS[M]) 2723 KnownZero.setBit(i); 2724 } else { 2725 if (UndefRHS[M - NumElts]) 2726 KnownUndef.setBit(i); 2727 if (ZeroRHS[M - NumElts]) 2728 KnownZero.setBit(i); 2729 } 2730 } 2731 break; 2732 } 2733 case ISD::ANY_EXTEND_VECTOR_INREG: 2734 case ISD::SIGN_EXTEND_VECTOR_INREG: 2735 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2736 APInt SrcUndef, SrcZero; 2737 SDValue Src = Op.getOperand(0); 2738 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2739 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2740 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2741 Depth + 1)) 2742 return true; 2743 KnownZero = SrcZero.zextOrTrunc(NumElts); 2744 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 2745 2746 if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 2747 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 2748 DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) { 2749 // aext - if we just need the bottom element then we can bitcast. 2750 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2751 } 2752 2753 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 2754 // zext(undef) upper bits are guaranteed to be zero. 2755 if (DemandedElts.isSubsetOf(KnownUndef)) 2756 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2757 KnownUndef.clearAllBits(); 2758 } 2759 break; 2760 } 2761 2762 // TODO: There are more binop opcodes that could be handled here - MIN, 2763 // MAX, saturated math, etc. 2764 case ISD::OR: 2765 case ISD::XOR: 2766 case ISD::ADD: 2767 case ISD::SUB: 2768 case ISD::FADD: 2769 case ISD::FSUB: 2770 case ISD::FMUL: 2771 case ISD::FDIV: 2772 case ISD::FREM: { 2773 SDValue Op0 = Op.getOperand(0); 2774 SDValue Op1 = Op.getOperand(1); 2775 2776 APInt UndefRHS, ZeroRHS; 2777 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2778 Depth + 1)) 2779 return true; 2780 APInt UndefLHS, ZeroLHS; 2781 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2782 Depth + 1)) 2783 return true; 2784 2785 KnownZero = ZeroLHS & ZeroRHS; 2786 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 2787 2788 // Attempt to avoid multi-use ops if we don't need anything from them. 2789 // TODO - use KnownUndef to relax the demandedelts? 2790 if (!DemandedElts.isAllOnesValue()) 2791 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2792 return true; 2793 break; 2794 } 2795 case ISD::SHL: 2796 case ISD::SRL: 2797 case ISD::SRA: 2798 case ISD::ROTL: 2799 case ISD::ROTR: { 2800 SDValue Op0 = Op.getOperand(0); 2801 SDValue Op1 = Op.getOperand(1); 2802 2803 APInt UndefRHS, ZeroRHS; 2804 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2805 Depth + 1)) 2806 return true; 2807 APInt UndefLHS, ZeroLHS; 2808 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2809 Depth + 1)) 2810 return true; 2811 2812 KnownZero = ZeroLHS; 2813 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 2814 2815 // Attempt to avoid multi-use ops if we don't need anything from them. 2816 // TODO - use KnownUndef to relax the demandedelts? 2817 if (!DemandedElts.isAllOnesValue()) 2818 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2819 return true; 2820 break; 2821 } 2822 case ISD::MUL: 2823 case ISD::AND: { 2824 SDValue Op0 = Op.getOperand(0); 2825 SDValue Op1 = Op.getOperand(1); 2826 2827 APInt SrcUndef, SrcZero; 2828 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 2829 Depth + 1)) 2830 return true; 2831 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 2832 TLO, Depth + 1)) 2833 return true; 2834 2835 // If either side has a zero element, then the result element is zero, even 2836 // if the other is an UNDEF. 2837 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 2838 // and then handle 'and' nodes with the rest of the binop opcodes. 2839 KnownZero |= SrcZero; 2840 KnownUndef &= SrcUndef; 2841 KnownUndef &= ~KnownZero; 2842 2843 // Attempt to avoid multi-use ops if we don't need anything from them. 2844 // TODO - use KnownUndef to relax the demandedelts? 2845 if (!DemandedElts.isAllOnesValue()) 2846 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2847 return true; 2848 break; 2849 } 2850 case ISD::TRUNCATE: 2851 case ISD::SIGN_EXTEND: 2852 case ISD::ZERO_EXTEND: 2853 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 2854 KnownZero, TLO, Depth + 1)) 2855 return true; 2856 2857 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 2858 // zext(undef) upper bits are guaranteed to be zero. 2859 if (DemandedElts.isSubsetOf(KnownUndef)) 2860 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2861 KnownUndef.clearAllBits(); 2862 } 2863 break; 2864 default: { 2865 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2866 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 2867 KnownZero, TLO, Depth)) 2868 return true; 2869 } else { 2870 KnownBits Known; 2871 APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits); 2872 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 2873 TLO, Depth, AssumeSingleUse)) 2874 return true; 2875 } 2876 break; 2877 } 2878 } 2879 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 2880 2881 // Constant fold all undef cases. 2882 // TODO: Handle zero cases as well. 2883 if (DemandedElts.isSubsetOf(KnownUndef)) 2884 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2885 2886 return false; 2887 } 2888 2889 /// Determine which of the bits specified in Mask are known to be either zero or 2890 /// one and return them in the Known. 2891 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 2892 KnownBits &Known, 2893 const APInt &DemandedElts, 2894 const SelectionDAG &DAG, 2895 unsigned Depth) const { 2896 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2897 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2898 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2899 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2900 "Should use MaskedValueIsZero if you don't know whether Op" 2901 " is a target node!"); 2902 Known.resetAll(); 2903 } 2904 2905 void TargetLowering::computeKnownBitsForTargetInstr( 2906 GISelKnownBits &Analysis, Register R, KnownBits &Known, 2907 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 2908 unsigned Depth) const { 2909 Known.resetAll(); 2910 } 2911 2912 void TargetLowering::computeKnownBitsForFrameIndex( 2913 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 2914 // The low bits are known zero if the pointer is aligned. 2915 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 2916 } 2917 2918 Align TargetLowering::computeKnownAlignForTargetInstr( 2919 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 2920 unsigned Depth) const { 2921 return Align(1); 2922 } 2923 2924 /// This method can be implemented by targets that want to expose additional 2925 /// information about sign bits to the DAG Combiner. 2926 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 2927 const APInt &, 2928 const SelectionDAG &, 2929 unsigned Depth) const { 2930 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2931 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2932 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2933 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2934 "Should use ComputeNumSignBits if you don't know whether Op" 2935 " is a target node!"); 2936 return 1; 2937 } 2938 2939 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 2940 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 2941 const MachineRegisterInfo &MRI, unsigned Depth) const { 2942 return 1; 2943 } 2944 2945 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 2946 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 2947 TargetLoweringOpt &TLO, unsigned Depth) const { 2948 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2949 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2950 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2951 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2952 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 2953 " is a target node!"); 2954 return false; 2955 } 2956 2957 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 2958 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2959 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 2960 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2961 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2962 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2963 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2964 "Should use SimplifyDemandedBits if you don't know whether Op" 2965 " is a target node!"); 2966 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 2967 return false; 2968 } 2969 2970 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 2971 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2972 SelectionDAG &DAG, unsigned Depth) const { 2973 assert( 2974 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2975 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2976 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2977 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2978 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 2979 " is a target node!"); 2980 return SDValue(); 2981 } 2982 2983 SDValue 2984 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 2985 SDValue N1, MutableArrayRef<int> Mask, 2986 SelectionDAG &DAG) const { 2987 bool LegalMask = isShuffleMaskLegal(Mask, VT); 2988 if (!LegalMask) { 2989 std::swap(N0, N1); 2990 ShuffleVectorSDNode::commuteMask(Mask); 2991 LegalMask = isShuffleMaskLegal(Mask, VT); 2992 } 2993 2994 if (!LegalMask) 2995 return SDValue(); 2996 2997 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 2998 } 2999 3000 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3001 return nullptr; 3002 } 3003 3004 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3005 const SelectionDAG &DAG, 3006 bool SNaN, 3007 unsigned Depth) const { 3008 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3009 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3010 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3011 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3012 "Should use isKnownNeverNaN if you don't know whether Op" 3013 " is a target node!"); 3014 return false; 3015 } 3016 3017 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3018 // work with truncating build vectors and vectors with elements of less than 3019 // 8 bits. 3020 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 3021 if (!N) 3022 return false; 3023 3024 APInt CVal; 3025 if (auto *CN = dyn_cast<ConstantSDNode>(N)) { 3026 CVal = CN->getAPIntValue(); 3027 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) { 3028 auto *CN = BV->getConstantSplatNode(); 3029 if (!CN) 3030 return false; 3031 3032 // If this is a truncating build vector, truncate the splat value. 3033 // Otherwise, we may fail to match the expected values below. 3034 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits(); 3035 CVal = CN->getAPIntValue(); 3036 if (BVEltWidth < CVal.getBitWidth()) 3037 CVal = CVal.trunc(BVEltWidth); 3038 } else { 3039 return false; 3040 } 3041 3042 switch (getBooleanContents(N->getValueType(0))) { 3043 case UndefinedBooleanContent: 3044 return CVal[0]; 3045 case ZeroOrOneBooleanContent: 3046 return CVal.isOneValue(); 3047 case ZeroOrNegativeOneBooleanContent: 3048 return CVal.isAllOnesValue(); 3049 } 3050 3051 llvm_unreachable("Invalid boolean contents"); 3052 } 3053 3054 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 3055 if (!N) 3056 return false; 3057 3058 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3059 if (!CN) { 3060 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3061 if (!BV) 3062 return false; 3063 3064 // Only interested in constant splats, we don't care about undef 3065 // elements in identifying boolean constants and getConstantSplatNode 3066 // returns NULL if all ops are undef; 3067 CN = BV->getConstantSplatNode(); 3068 if (!CN) 3069 return false; 3070 } 3071 3072 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3073 return !CN->getAPIntValue()[0]; 3074 3075 return CN->isNullValue(); 3076 } 3077 3078 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3079 bool SExt) const { 3080 if (VT == MVT::i1) 3081 return N->isOne(); 3082 3083 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3084 switch (Cnt) { 3085 case TargetLowering::ZeroOrOneBooleanContent: 3086 // An extended value of 1 is always true, unless its original type is i1, 3087 // in which case it will be sign extended to -1. 3088 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3089 case TargetLowering::UndefinedBooleanContent: 3090 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3091 return N->isAllOnesValue() && SExt; 3092 } 3093 llvm_unreachable("Unexpected enumeration."); 3094 } 3095 3096 /// This helper function of SimplifySetCC tries to optimize the comparison when 3097 /// either operand of the SetCC node is a bitwise-and instruction. 3098 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3099 ISD::CondCode Cond, const SDLoc &DL, 3100 DAGCombinerInfo &DCI) const { 3101 // Match these patterns in any of their permutations: 3102 // (X & Y) == Y 3103 // (X & Y) != Y 3104 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3105 std::swap(N0, N1); 3106 3107 EVT OpVT = N0.getValueType(); 3108 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3109 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3110 return SDValue(); 3111 3112 SDValue X, Y; 3113 if (N0.getOperand(0) == N1) { 3114 X = N0.getOperand(1); 3115 Y = N0.getOperand(0); 3116 } else if (N0.getOperand(1) == N1) { 3117 X = N0.getOperand(0); 3118 Y = N0.getOperand(1); 3119 } else { 3120 return SDValue(); 3121 } 3122 3123 SelectionDAG &DAG = DCI.DAG; 3124 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3125 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3126 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3127 // Note that where Y is variable and is known to have at most one bit set 3128 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3129 // equivalent when Y == 0. 3130 assert(OpVT.isInteger()); 3131 Cond = ISD::getSetCCInverse(Cond, OpVT); 3132 if (DCI.isBeforeLegalizeOps() || 3133 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3134 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3135 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3136 // If the target supports an 'and-not' or 'and-complement' logic operation, 3137 // try to use that to make a comparison operation more efficient. 3138 // But don't do this transform if the mask is a single bit because there are 3139 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3140 // 'rlwinm' on PPC). 3141 3142 // Bail out if the compare operand that we want to turn into a zero is 3143 // already a zero (otherwise, infinite loop). 3144 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3145 if (YConst && YConst->isNullValue()) 3146 return SDValue(); 3147 3148 // Transform this into: ~X & Y == 0. 3149 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3150 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3151 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3152 } 3153 3154 return SDValue(); 3155 } 3156 3157 /// There are multiple IR patterns that could be checking whether certain 3158 /// truncation of a signed number would be lossy or not. The pattern which is 3159 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3160 /// We are looking for the following pattern: (KeptBits is a constant) 3161 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3162 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3163 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3164 /// We will unfold it into the natural trunc+sext pattern: 3165 /// ((%x << C) a>> C) dstcond %x 3166 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3167 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3168 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3169 const SDLoc &DL) const { 3170 // We must be comparing with a constant. 3171 ConstantSDNode *C1; 3172 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3173 return SDValue(); 3174 3175 // N0 should be: add %x, (1 << (KeptBits-1)) 3176 if (N0->getOpcode() != ISD::ADD) 3177 return SDValue(); 3178 3179 // And we must be 'add'ing a constant. 3180 ConstantSDNode *C01; 3181 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3182 return SDValue(); 3183 3184 SDValue X = N0->getOperand(0); 3185 EVT XVT = X.getValueType(); 3186 3187 // Validate constants ... 3188 3189 APInt I1 = C1->getAPIntValue(); 3190 3191 ISD::CondCode NewCond; 3192 if (Cond == ISD::CondCode::SETULT) { 3193 NewCond = ISD::CondCode::SETEQ; 3194 } else if (Cond == ISD::CondCode::SETULE) { 3195 NewCond = ISD::CondCode::SETEQ; 3196 // But need to 'canonicalize' the constant. 3197 I1 += 1; 3198 } else if (Cond == ISD::CondCode::SETUGT) { 3199 NewCond = ISD::CondCode::SETNE; 3200 // But need to 'canonicalize' the constant. 3201 I1 += 1; 3202 } else if (Cond == ISD::CondCode::SETUGE) { 3203 NewCond = ISD::CondCode::SETNE; 3204 } else 3205 return SDValue(); 3206 3207 APInt I01 = C01->getAPIntValue(); 3208 3209 auto checkConstants = [&I1, &I01]() -> bool { 3210 // Both of them must be power-of-two, and the constant from setcc is bigger. 3211 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3212 }; 3213 3214 if (checkConstants()) { 3215 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3216 } else { 3217 // What if we invert constants? (and the target predicate) 3218 I1.negate(); 3219 I01.negate(); 3220 assert(XVT.isInteger()); 3221 NewCond = getSetCCInverse(NewCond, XVT); 3222 if (!checkConstants()) 3223 return SDValue(); 3224 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3225 } 3226 3227 // They are power-of-two, so which bit is set? 3228 const unsigned KeptBits = I1.logBase2(); 3229 const unsigned KeptBitsMinusOne = I01.logBase2(); 3230 3231 // Magic! 3232 if (KeptBits != (KeptBitsMinusOne + 1)) 3233 return SDValue(); 3234 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3235 3236 // We don't want to do this in every single case. 3237 SelectionDAG &DAG = DCI.DAG; 3238 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3239 XVT, KeptBits)) 3240 return SDValue(); 3241 3242 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3243 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3244 3245 // Unfold into: ((%x << C) a>> C) cond %x 3246 // Where 'cond' will be either 'eq' or 'ne'. 3247 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3248 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3249 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3250 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3251 3252 return T2; 3253 } 3254 3255 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3256 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3257 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3258 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3259 assert(isConstOrConstSplat(N1C) && 3260 isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() && 3261 "Should be a comparison with 0."); 3262 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3263 "Valid only for [in]equality comparisons."); 3264 3265 unsigned NewShiftOpcode; 3266 SDValue X, C, Y; 3267 3268 SelectionDAG &DAG = DCI.DAG; 3269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3270 3271 // Look for '(C l>>/<< Y)'. 3272 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3273 // The shift should be one-use. 3274 if (!V.hasOneUse()) 3275 return false; 3276 unsigned OldShiftOpcode = V.getOpcode(); 3277 switch (OldShiftOpcode) { 3278 case ISD::SHL: 3279 NewShiftOpcode = ISD::SRL; 3280 break; 3281 case ISD::SRL: 3282 NewShiftOpcode = ISD::SHL; 3283 break; 3284 default: 3285 return false; // must be a logical shift. 3286 } 3287 // We should be shifting a constant. 3288 // FIXME: best to use isConstantOrConstantVector(). 3289 C = V.getOperand(0); 3290 ConstantSDNode *CC = 3291 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3292 if (!CC) 3293 return false; 3294 Y = V.getOperand(1); 3295 3296 ConstantSDNode *XC = 3297 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3298 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3299 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3300 }; 3301 3302 // LHS of comparison should be an one-use 'and'. 3303 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3304 return SDValue(); 3305 3306 X = N0.getOperand(0); 3307 SDValue Mask = N0.getOperand(1); 3308 3309 // 'and' is commutative! 3310 if (!Match(Mask)) { 3311 std::swap(X, Mask); 3312 if (!Match(Mask)) 3313 return SDValue(); 3314 } 3315 3316 EVT VT = X.getValueType(); 3317 3318 // Produce: 3319 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3320 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3321 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3322 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3323 return T2; 3324 } 3325 3326 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3327 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3328 /// handle the commuted versions of these patterns. 3329 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3330 ISD::CondCode Cond, const SDLoc &DL, 3331 DAGCombinerInfo &DCI) const { 3332 unsigned BOpcode = N0.getOpcode(); 3333 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3334 "Unexpected binop"); 3335 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3336 3337 // (X + Y) == X --> Y == 0 3338 // (X - Y) == X --> Y == 0 3339 // (X ^ Y) == X --> Y == 0 3340 SelectionDAG &DAG = DCI.DAG; 3341 EVT OpVT = N0.getValueType(); 3342 SDValue X = N0.getOperand(0); 3343 SDValue Y = N0.getOperand(1); 3344 if (X == N1) 3345 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3346 3347 if (Y != N1) 3348 return SDValue(); 3349 3350 // (X + Y) == Y --> X == 0 3351 // (X ^ Y) == Y --> X == 0 3352 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3353 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3354 3355 // The shift would not be valid if the operands are boolean (i1). 3356 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3357 return SDValue(); 3358 3359 // (X - Y) == Y --> X == Y << 1 3360 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3361 !DCI.isBeforeLegalize()); 3362 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3363 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3364 if (!DCI.isCalledByLegalizer()) 3365 DCI.AddToWorklist(YShl1.getNode()); 3366 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3367 } 3368 3369 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3370 SDValue N0, const APInt &C1, 3371 ISD::CondCode Cond, const SDLoc &dl, 3372 SelectionDAG &DAG) { 3373 // Look through truncs that don't change the value of a ctpop. 3374 // FIXME: Add vector support? Need to be careful with setcc result type below. 3375 SDValue CTPOP = N0; 3376 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3377 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3378 CTPOP = N0.getOperand(0); 3379 3380 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3381 return SDValue(); 3382 3383 EVT CTVT = CTPOP.getValueType(); 3384 SDValue CTOp = CTPOP.getOperand(0); 3385 3386 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3387 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3388 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3389 return SDValue(); 3390 3391 // (ctpop x) u< 2 -> (x & x-1) == 0 3392 // (ctpop x) u> 1 -> (x & x-1) != 0 3393 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3394 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3395 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3396 return SDValue(); 3397 if (C1 == 0 && (Cond == ISD::SETULT)) 3398 return SDValue(); // This is handled elsewhere. 3399 3400 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3401 3402 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3403 SDValue Result = CTOp; 3404 for (unsigned i = 0; i < Passes; i++) { 3405 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3406 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3407 } 3408 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3409 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3410 } 3411 3412 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3413 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3414 // For scalars, keep CTPOP if it is legal or custom. 3415 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3416 return SDValue(); 3417 // This is based on X86's custom lowering for CTPOP which produces more 3418 // instructions than the expansion here. 3419 3420 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3421 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3422 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3423 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3424 assert(CTVT.isInteger()); 3425 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3426 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3427 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3428 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3429 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3430 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3431 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3432 } 3433 3434 return SDValue(); 3435 } 3436 3437 /// Try to simplify a setcc built with the specified operands and cc. If it is 3438 /// unable to simplify it, return a null SDValue. 3439 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3440 ISD::CondCode Cond, bool foldBooleans, 3441 DAGCombinerInfo &DCI, 3442 const SDLoc &dl) const { 3443 SelectionDAG &DAG = DCI.DAG; 3444 const DataLayout &Layout = DAG.getDataLayout(); 3445 EVT OpVT = N0.getValueType(); 3446 3447 // Constant fold or commute setcc. 3448 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 3449 return Fold; 3450 3451 // Ensure that the constant occurs on the RHS and fold constant comparisons. 3452 // TODO: Handle non-splat vector constants. All undef causes trouble. 3453 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 3454 // infinite loop here when we encounter one. 3455 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 3456 if (isConstOrConstSplat(N0) && 3457 (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) && 3458 (DCI.isBeforeLegalizeOps() || 3459 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 3460 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3461 3462 // If we have a subtract with the same 2 non-constant operands as this setcc 3463 // -- but in reverse order -- then try to commute the operands of this setcc 3464 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 3465 // instruction on some targets. 3466 if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) && 3467 (DCI.isBeforeLegalizeOps() || 3468 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 3469 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 3470 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 3471 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3472 3473 if (auto *N1C = isConstOrConstSplat(N1)) { 3474 const APInt &C1 = N1C->getAPIntValue(); 3475 3476 // Optimize some CTPOP cases. 3477 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 3478 return V; 3479 3480 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 3481 // equality comparison, then we're just comparing whether X itself is 3482 // zero. 3483 if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) && 3484 N0.getOperand(0).getOpcode() == ISD::CTLZ && 3485 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 3486 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 3487 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3488 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 3489 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 3490 // (srl (ctlz x), 5) == 0 -> X != 0 3491 // (srl (ctlz x), 5) != 1 -> X != 0 3492 Cond = ISD::SETNE; 3493 } else { 3494 // (srl (ctlz x), 5) != 0 -> X == 0 3495 // (srl (ctlz x), 5) == 1 -> X == 0 3496 Cond = ISD::SETEQ; 3497 } 3498 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 3499 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 3500 Cond); 3501 } 3502 } 3503 } 3504 } 3505 3506 // FIXME: Support vectors. 3507 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 3508 const APInt &C1 = N1C->getAPIntValue(); 3509 3510 // (zext x) == C --> x == (trunc C) 3511 // (sext x) == C --> x == (trunc C) 3512 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3513 DCI.isBeforeLegalize() && N0->hasOneUse()) { 3514 unsigned MinBits = N0.getValueSizeInBits(); 3515 SDValue PreExt; 3516 bool Signed = false; 3517 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 3518 // ZExt 3519 MinBits = N0->getOperand(0).getValueSizeInBits(); 3520 PreExt = N0->getOperand(0); 3521 } else if (N0->getOpcode() == ISD::AND) { 3522 // DAGCombine turns costly ZExts into ANDs 3523 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 3524 if ((C->getAPIntValue()+1).isPowerOf2()) { 3525 MinBits = C->getAPIntValue().countTrailingOnes(); 3526 PreExt = N0->getOperand(0); 3527 } 3528 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 3529 // SExt 3530 MinBits = N0->getOperand(0).getValueSizeInBits(); 3531 PreExt = N0->getOperand(0); 3532 Signed = true; 3533 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 3534 // ZEXTLOAD / SEXTLOAD 3535 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 3536 MinBits = LN0->getMemoryVT().getSizeInBits(); 3537 PreExt = N0; 3538 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 3539 Signed = true; 3540 MinBits = LN0->getMemoryVT().getSizeInBits(); 3541 PreExt = N0; 3542 } 3543 } 3544 3545 // Figure out how many bits we need to preserve this constant. 3546 unsigned ReqdBits = Signed ? 3547 C1.getBitWidth() - C1.getNumSignBits() + 1 : 3548 C1.getActiveBits(); 3549 3550 // Make sure we're not losing bits from the constant. 3551 if (MinBits > 0 && 3552 MinBits < C1.getBitWidth() && 3553 MinBits >= ReqdBits) { 3554 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 3555 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 3556 // Will get folded away. 3557 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 3558 if (MinBits == 1 && C1 == 1) 3559 // Invert the condition. 3560 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 3561 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3562 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 3563 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 3564 } 3565 3566 // If truncating the setcc operands is not desirable, we can still 3567 // simplify the expression in some cases: 3568 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 3569 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 3570 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 3571 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 3572 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 3573 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 3574 SDValue TopSetCC = N0->getOperand(0); 3575 unsigned N0Opc = N0->getOpcode(); 3576 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 3577 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 3578 TopSetCC.getOpcode() == ISD::SETCC && 3579 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 3580 (isConstFalseVal(N1C) || 3581 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 3582 3583 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 3584 (!N1C->isNullValue() && Cond == ISD::SETNE); 3585 3586 if (!Inverse) 3587 return TopSetCC; 3588 3589 ISD::CondCode InvCond = ISD::getSetCCInverse( 3590 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 3591 TopSetCC.getOperand(0).getValueType()); 3592 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 3593 TopSetCC.getOperand(1), 3594 InvCond); 3595 } 3596 } 3597 } 3598 3599 // If the LHS is '(and load, const)', the RHS is 0, the test is for 3600 // equality or unsigned, and all 1 bits of the const are in the same 3601 // partial word, see if we can shorten the load. 3602 if (DCI.isBeforeLegalize() && 3603 !ISD::isSignedIntSetCC(Cond) && 3604 N0.getOpcode() == ISD::AND && C1 == 0 && 3605 N0.getNode()->hasOneUse() && 3606 isa<LoadSDNode>(N0.getOperand(0)) && 3607 N0.getOperand(0).getNode()->hasOneUse() && 3608 isa<ConstantSDNode>(N0.getOperand(1))) { 3609 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 3610 APInt bestMask; 3611 unsigned bestWidth = 0, bestOffset = 0; 3612 if (Lod->isSimple() && Lod->isUnindexed()) { 3613 unsigned origWidth = N0.getValueSizeInBits(); 3614 unsigned maskWidth = origWidth; 3615 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 3616 // 8 bits, but have to be careful... 3617 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 3618 origWidth = Lod->getMemoryVT().getSizeInBits(); 3619 const APInt &Mask = N0.getConstantOperandAPInt(1); 3620 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 3621 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 3622 for (unsigned offset=0; offset<origWidth/width; offset++) { 3623 if (Mask.isSubsetOf(newMask)) { 3624 if (Layout.isLittleEndian()) 3625 bestOffset = (uint64_t)offset * (width/8); 3626 else 3627 bestOffset = (origWidth/width - offset - 1) * (width/8); 3628 bestMask = Mask.lshr(offset * (width/8) * 8); 3629 bestWidth = width; 3630 break; 3631 } 3632 newMask <<= width; 3633 } 3634 } 3635 } 3636 if (bestWidth) { 3637 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 3638 if (newVT.isRound() && 3639 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 3640 SDValue Ptr = Lod->getBasePtr(); 3641 if (bestOffset != 0) 3642 Ptr = 3643 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 3644 SDValue NewLoad = 3645 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 3646 Lod->getPointerInfo().getWithOffset(bestOffset), 3647 Lod->getOriginalAlign()); 3648 return DAG.getSetCC(dl, VT, 3649 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 3650 DAG.getConstant(bestMask.trunc(bestWidth), 3651 dl, newVT)), 3652 DAG.getConstant(0LL, dl, newVT), Cond); 3653 } 3654 } 3655 } 3656 3657 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 3658 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 3659 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 3660 3661 // If the comparison constant has bits in the upper part, the 3662 // zero-extended value could never match. 3663 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 3664 C1.getBitWidth() - InSize))) { 3665 switch (Cond) { 3666 case ISD::SETUGT: 3667 case ISD::SETUGE: 3668 case ISD::SETEQ: 3669 return DAG.getConstant(0, dl, VT); 3670 case ISD::SETULT: 3671 case ISD::SETULE: 3672 case ISD::SETNE: 3673 return DAG.getConstant(1, dl, VT); 3674 case ISD::SETGT: 3675 case ISD::SETGE: 3676 // True if the sign bit of C1 is set. 3677 return DAG.getConstant(C1.isNegative(), dl, VT); 3678 case ISD::SETLT: 3679 case ISD::SETLE: 3680 // True if the sign bit of C1 isn't set. 3681 return DAG.getConstant(C1.isNonNegative(), dl, VT); 3682 default: 3683 break; 3684 } 3685 } 3686 3687 // Otherwise, we can perform the comparison with the low bits. 3688 switch (Cond) { 3689 case ISD::SETEQ: 3690 case ISD::SETNE: 3691 case ISD::SETUGT: 3692 case ISD::SETUGE: 3693 case ISD::SETULT: 3694 case ISD::SETULE: { 3695 EVT newVT = N0.getOperand(0).getValueType(); 3696 if (DCI.isBeforeLegalizeOps() || 3697 (isOperationLegal(ISD::SETCC, newVT) && 3698 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 3699 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 3700 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 3701 3702 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 3703 NewConst, Cond); 3704 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 3705 } 3706 break; 3707 } 3708 default: 3709 break; // todo, be more careful with signed comparisons 3710 } 3711 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 3712 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3713 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 3714 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 3715 EVT ExtDstTy = N0.getValueType(); 3716 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 3717 3718 // If the constant doesn't fit into the number of bits for the source of 3719 // the sign extension, it is impossible for both sides to be equal. 3720 if (C1.getMinSignedBits() > ExtSrcTyBits) 3721 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 3722 3723 SDValue ZextOp; 3724 EVT Op0Ty = N0.getOperand(0).getValueType(); 3725 if (Op0Ty == ExtSrcTy) { 3726 ZextOp = N0.getOperand(0); 3727 } else { 3728 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 3729 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 3730 DAG.getConstant(Imm, dl, Op0Ty)); 3731 } 3732 if (!DCI.isCalledByLegalizer()) 3733 DCI.AddToWorklist(ZextOp.getNode()); 3734 // Otherwise, make this a use of a zext. 3735 return DAG.getSetCC(dl, VT, ZextOp, 3736 DAG.getConstant(C1 & APInt::getLowBitsSet( 3737 ExtDstTyBits, 3738 ExtSrcTyBits), 3739 dl, ExtDstTy), 3740 Cond); 3741 } else if ((N1C->isNullValue() || N1C->isOne()) && 3742 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3743 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 3744 if (N0.getOpcode() == ISD::SETCC && 3745 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 3746 (N0.getValueType() == MVT::i1 || 3747 getBooleanContents(N0.getOperand(0).getValueType()) == 3748 ZeroOrOneBooleanContent)) { 3749 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 3750 if (TrueWhenTrue) 3751 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 3752 // Invert the condition. 3753 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 3754 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 3755 if (DCI.isBeforeLegalizeOps() || 3756 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 3757 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 3758 } 3759 3760 if ((N0.getOpcode() == ISD::XOR || 3761 (N0.getOpcode() == ISD::AND && 3762 N0.getOperand(0).getOpcode() == ISD::XOR && 3763 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 3764 isa<ConstantSDNode>(N0.getOperand(1)) && 3765 cast<ConstantSDNode>(N0.getOperand(1))->isOne()) { 3766 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 3767 // can only do this if the top bits are known zero. 3768 unsigned BitWidth = N0.getValueSizeInBits(); 3769 if (DAG.MaskedValueIsZero(N0, 3770 APInt::getHighBitsSet(BitWidth, 3771 BitWidth-1))) { 3772 // Okay, get the un-inverted input value. 3773 SDValue Val; 3774 if (N0.getOpcode() == ISD::XOR) { 3775 Val = N0.getOperand(0); 3776 } else { 3777 assert(N0.getOpcode() == ISD::AND && 3778 N0.getOperand(0).getOpcode() == ISD::XOR); 3779 // ((X^1)&1)^1 -> X & 1 3780 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 3781 N0.getOperand(0).getOperand(0), 3782 N0.getOperand(1)); 3783 } 3784 3785 return DAG.getSetCC(dl, VT, Val, N1, 3786 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3787 } 3788 } else if (N1C->isOne()) { 3789 SDValue Op0 = N0; 3790 if (Op0.getOpcode() == ISD::TRUNCATE) 3791 Op0 = Op0.getOperand(0); 3792 3793 if ((Op0.getOpcode() == ISD::XOR) && 3794 Op0.getOperand(0).getOpcode() == ISD::SETCC && 3795 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 3796 SDValue XorLHS = Op0.getOperand(0); 3797 SDValue XorRHS = Op0.getOperand(1); 3798 // Ensure that the input setccs return an i1 type or 0/1 value. 3799 if (Op0.getValueType() == MVT::i1 || 3800 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 3801 ZeroOrOneBooleanContent && 3802 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 3803 ZeroOrOneBooleanContent)) { 3804 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 3805 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 3806 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 3807 } 3808 } 3809 if (Op0.getOpcode() == ISD::AND && 3810 isa<ConstantSDNode>(Op0.getOperand(1)) && 3811 cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) { 3812 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 3813 if (Op0.getValueType().bitsGT(VT)) 3814 Op0 = DAG.getNode(ISD::AND, dl, VT, 3815 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 3816 DAG.getConstant(1, dl, VT)); 3817 else if (Op0.getValueType().bitsLT(VT)) 3818 Op0 = DAG.getNode(ISD::AND, dl, VT, 3819 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 3820 DAG.getConstant(1, dl, VT)); 3821 3822 return DAG.getSetCC(dl, VT, Op0, 3823 DAG.getConstant(0, dl, Op0.getValueType()), 3824 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3825 } 3826 if (Op0.getOpcode() == ISD::AssertZext && 3827 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 3828 return DAG.getSetCC(dl, VT, Op0, 3829 DAG.getConstant(0, dl, Op0.getValueType()), 3830 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3831 } 3832 } 3833 3834 // Given: 3835 // icmp eq/ne (urem %x, %y), 0 3836 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 3837 // icmp eq/ne %x, 0 3838 if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() && 3839 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3840 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 3841 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 3842 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 3843 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 3844 } 3845 3846 if (SDValue V = 3847 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 3848 return V; 3849 } 3850 3851 // These simplifications apply to splat vectors as well. 3852 // TODO: Handle more splat vector cases. 3853 if (auto *N1C = isConstOrConstSplat(N1)) { 3854 const APInt &C1 = N1C->getAPIntValue(); 3855 3856 APInt MinVal, MaxVal; 3857 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 3858 if (ISD::isSignedIntSetCC(Cond)) { 3859 MinVal = APInt::getSignedMinValue(OperandBitSize); 3860 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 3861 } else { 3862 MinVal = APInt::getMinValue(OperandBitSize); 3863 MaxVal = APInt::getMaxValue(OperandBitSize); 3864 } 3865 3866 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 3867 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 3868 // X >= MIN --> true 3869 if (C1 == MinVal) 3870 return DAG.getBoolConstant(true, dl, VT, OpVT); 3871 3872 if (!VT.isVector()) { // TODO: Support this for vectors. 3873 // X >= C0 --> X > (C0 - 1) 3874 APInt C = C1 - 1; 3875 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 3876 if ((DCI.isBeforeLegalizeOps() || 3877 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3878 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3879 isLegalICmpImmediate(C.getSExtValue())))) { 3880 return DAG.getSetCC(dl, VT, N0, 3881 DAG.getConstant(C, dl, N1.getValueType()), 3882 NewCC); 3883 } 3884 } 3885 } 3886 3887 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 3888 // X <= MAX --> true 3889 if (C1 == MaxVal) 3890 return DAG.getBoolConstant(true, dl, VT, OpVT); 3891 3892 // X <= C0 --> X < (C0 + 1) 3893 if (!VT.isVector()) { // TODO: Support this for vectors. 3894 APInt C = C1 + 1; 3895 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 3896 if ((DCI.isBeforeLegalizeOps() || 3897 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3898 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3899 isLegalICmpImmediate(C.getSExtValue())))) { 3900 return DAG.getSetCC(dl, VT, N0, 3901 DAG.getConstant(C, dl, N1.getValueType()), 3902 NewCC); 3903 } 3904 } 3905 } 3906 3907 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 3908 if (C1 == MinVal) 3909 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 3910 3911 // TODO: Support this for vectors after legalize ops. 3912 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3913 // Canonicalize setlt X, Max --> setne X, Max 3914 if (C1 == MaxVal) 3915 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3916 3917 // If we have setult X, 1, turn it into seteq X, 0 3918 if (C1 == MinVal+1) 3919 return DAG.getSetCC(dl, VT, N0, 3920 DAG.getConstant(MinVal, dl, N0.getValueType()), 3921 ISD::SETEQ); 3922 } 3923 } 3924 3925 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 3926 if (C1 == MaxVal) 3927 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 3928 3929 // TODO: Support this for vectors after legalize ops. 3930 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3931 // Canonicalize setgt X, Min --> setne X, Min 3932 if (C1 == MinVal) 3933 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3934 3935 // If we have setugt X, Max-1, turn it into seteq X, Max 3936 if (C1 == MaxVal-1) 3937 return DAG.getSetCC(dl, VT, N0, 3938 DAG.getConstant(MaxVal, dl, N0.getValueType()), 3939 ISD::SETEQ); 3940 } 3941 } 3942 3943 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 3944 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3945 if (C1.isNullValue()) 3946 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 3947 VT, N0, N1, Cond, DCI, dl)) 3948 return CC; 3949 3950 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 3951 // For example, when high 32-bits of i64 X are known clear: 3952 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 3953 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 3954 bool CmpZero = N1C->getAPIntValue().isNullValue(); 3955 bool CmpNegOne = N1C->getAPIntValue().isAllOnesValue(); 3956 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 3957 // Match or(lo,shl(hi,bw/2)) pattern. 3958 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 3959 unsigned EltBits = V.getScalarValueSizeInBits(); 3960 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 3961 return false; 3962 SDValue LHS = V.getOperand(0); 3963 SDValue RHS = V.getOperand(1); 3964 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 3965 // Unshifted element must have zero upperbits. 3966 if (RHS.getOpcode() == ISD::SHL && 3967 isa<ConstantSDNode>(RHS.getOperand(1)) && 3968 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3969 DAG.MaskedValueIsZero(LHS, HiBits)) { 3970 Lo = LHS; 3971 Hi = RHS.getOperand(0); 3972 return true; 3973 } 3974 if (LHS.getOpcode() == ISD::SHL && 3975 isa<ConstantSDNode>(LHS.getOperand(1)) && 3976 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3977 DAG.MaskedValueIsZero(RHS, HiBits)) { 3978 Lo = RHS; 3979 Hi = LHS.getOperand(0); 3980 return true; 3981 } 3982 return false; 3983 }; 3984 3985 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 3986 unsigned EltBits = N0.getScalarValueSizeInBits(); 3987 unsigned HalfBits = EltBits / 2; 3988 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 3989 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 3990 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 3991 SDValue NewN0 = 3992 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 3993 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 3994 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 3995 }; 3996 3997 SDValue Lo, Hi; 3998 if (IsConcat(N0, Lo, Hi)) 3999 return MergeConcat(Lo, Hi); 4000 4001 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4002 SDValue Lo0, Lo1, Hi0, Hi1; 4003 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4004 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4005 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4006 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4007 } 4008 } 4009 } 4010 } 4011 4012 // If we have "setcc X, C0", check to see if we can shrink the immediate 4013 // by changing cc. 4014 // TODO: Support this for vectors after legalize ops. 4015 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4016 // SETUGT X, SINTMAX -> SETLT X, 0 4017 // SETUGE X, SINTMIN -> SETLT X, 0 4018 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4019 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4020 return DAG.getSetCC(dl, VT, N0, 4021 DAG.getConstant(0, dl, N1.getValueType()), 4022 ISD::SETLT); 4023 4024 // SETULT X, SINTMIN -> SETGT X, -1 4025 // SETULE X, SINTMAX -> SETGT X, -1 4026 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4027 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4028 return DAG.getSetCC(dl, VT, N0, 4029 DAG.getAllOnesConstant(dl, N1.getValueType()), 4030 ISD::SETGT); 4031 } 4032 } 4033 4034 // Back to non-vector simplifications. 4035 // TODO: Can we do these for vector splats? 4036 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4037 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4038 const APInt &C1 = N1C->getAPIntValue(); 4039 EVT ShValTy = N0.getValueType(); 4040 4041 // Fold bit comparisons when we can. This will result in an 4042 // incorrect value when boolean false is negative one, unless 4043 // the bitsize is 1 in which case the false value is the same 4044 // in practice regardless of the representation. 4045 if ((VT.getSizeInBits() == 1 || 4046 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4047 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4048 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4049 N0.getOpcode() == ISD::AND) { 4050 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4051 EVT ShiftTy = 4052 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4053 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4054 // Perform the xform if the AND RHS is a single bit. 4055 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4056 if (AndRHS->getAPIntValue().isPowerOf2() && 4057 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4058 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4059 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4060 DAG.getConstant(ShCt, dl, ShiftTy))); 4061 } 4062 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4063 // (X & 8) == 8 --> (X & 8) >> 3 4064 // Perform the xform if C1 is a single bit. 4065 unsigned ShCt = C1.logBase2(); 4066 if (C1.isPowerOf2() && 4067 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4068 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4069 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4070 DAG.getConstant(ShCt, dl, ShiftTy))); 4071 } 4072 } 4073 } 4074 } 4075 4076 if (C1.getMinSignedBits() <= 64 && 4077 !isLegalICmpImmediate(C1.getSExtValue())) { 4078 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4079 // (X & -256) == 256 -> (X >> 8) == 1 4080 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4081 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4082 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4083 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4084 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 4085 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4086 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4087 SDValue Shift = 4088 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4089 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4090 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4091 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4092 } 4093 } 4094 } 4095 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4096 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4097 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4098 // X < 0x100000000 -> (X >> 32) < 1 4099 // X >= 0x100000000 -> (X >> 32) >= 1 4100 // X <= 0x0ffffffff -> (X >> 32) < 1 4101 // X > 0x0ffffffff -> (X >> 32) >= 1 4102 unsigned ShiftBits; 4103 APInt NewC = C1; 4104 ISD::CondCode NewCond = Cond; 4105 if (AdjOne) { 4106 ShiftBits = C1.countTrailingOnes(); 4107 NewC = NewC + 1; 4108 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4109 } else { 4110 ShiftBits = C1.countTrailingZeros(); 4111 } 4112 NewC.lshrInPlace(ShiftBits); 4113 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4114 isLegalICmpImmediate(NewC.getSExtValue()) && 4115 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4116 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4117 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4118 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4119 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4120 } 4121 } 4122 } 4123 } 4124 4125 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4126 auto *CFP = cast<ConstantFPSDNode>(N1); 4127 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4128 4129 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4130 // constant if knowing that the operand is non-nan is enough. We prefer to 4131 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4132 // materialize 0.0. 4133 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4134 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4135 4136 // setcc (fneg x), C -> setcc swap(pred) x, -C 4137 if (N0.getOpcode() == ISD::FNEG) { 4138 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4139 if (DCI.isBeforeLegalizeOps() || 4140 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4141 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4142 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4143 } 4144 } 4145 4146 // If the condition is not legal, see if we can find an equivalent one 4147 // which is legal. 4148 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4149 // If the comparison was an awkward floating-point == or != and one of 4150 // the comparison operands is infinity or negative infinity, convert the 4151 // condition to a less-awkward <= or >=. 4152 if (CFP->getValueAPF().isInfinity()) { 4153 bool IsNegInf = CFP->getValueAPF().isNegative(); 4154 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4155 switch (Cond) { 4156 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4157 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4158 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4159 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4160 default: break; 4161 } 4162 if (NewCond != ISD::SETCC_INVALID && 4163 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4164 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4165 } 4166 } 4167 } 4168 4169 if (N0 == N1) { 4170 // The sext(setcc()) => setcc() optimization relies on the appropriate 4171 // constant being emitted. 4172 assert(!N0.getValueType().isInteger() && 4173 "Integer types should be handled by FoldSetCC"); 4174 4175 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4176 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4177 if (UOF == 2) // FP operators that are undefined on NaNs. 4178 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4179 if (UOF == unsigned(EqTrue)) 4180 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4181 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4182 // if it is not already. 4183 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4184 if (NewCond != Cond && 4185 (DCI.isBeforeLegalizeOps() || 4186 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4187 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4188 } 4189 4190 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4191 N0.getValueType().isInteger()) { 4192 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4193 N0.getOpcode() == ISD::XOR) { 4194 // Simplify (X+Y) == (X+Z) --> Y == Z 4195 if (N0.getOpcode() == N1.getOpcode()) { 4196 if (N0.getOperand(0) == N1.getOperand(0)) 4197 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4198 if (N0.getOperand(1) == N1.getOperand(1)) 4199 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4200 if (isCommutativeBinOp(N0.getOpcode())) { 4201 // If X op Y == Y op X, try other combinations. 4202 if (N0.getOperand(0) == N1.getOperand(1)) 4203 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4204 Cond); 4205 if (N0.getOperand(1) == N1.getOperand(0)) 4206 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4207 Cond); 4208 } 4209 } 4210 4211 // If RHS is a legal immediate value for a compare instruction, we need 4212 // to be careful about increasing register pressure needlessly. 4213 bool LegalRHSImm = false; 4214 4215 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4216 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4217 // Turn (X+C1) == C2 --> X == C2-C1 4218 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 4219 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4220 DAG.getConstant(RHSC->getAPIntValue()- 4221 LHSR->getAPIntValue(), 4222 dl, N0.getValueType()), Cond); 4223 } 4224 4225 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 4226 if (N0.getOpcode() == ISD::XOR) 4227 // If we know that all of the inverted bits are zero, don't bother 4228 // performing the inversion. 4229 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 4230 return 4231 DAG.getSetCC(dl, VT, N0.getOperand(0), 4232 DAG.getConstant(LHSR->getAPIntValue() ^ 4233 RHSC->getAPIntValue(), 4234 dl, N0.getValueType()), 4235 Cond); 4236 } 4237 4238 // Turn (C1-X) == C2 --> X == C1-C2 4239 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 4240 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 4241 return 4242 DAG.getSetCC(dl, VT, N0.getOperand(1), 4243 DAG.getConstant(SUBC->getAPIntValue() - 4244 RHSC->getAPIntValue(), 4245 dl, N0.getValueType()), 4246 Cond); 4247 } 4248 } 4249 4250 // Could RHSC fold directly into a compare? 4251 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4252 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4253 } 4254 4255 // (X+Y) == X --> Y == 0 and similar folds. 4256 // Don't do this if X is an immediate that can fold into a cmp 4257 // instruction and X+Y has other uses. It could be an induction variable 4258 // chain, and the transform would increase register pressure. 4259 if (!LegalRHSImm || N0.hasOneUse()) 4260 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4261 return V; 4262 } 4263 4264 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4265 N1.getOpcode() == ISD::XOR) 4266 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4267 return V; 4268 4269 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4270 return V; 4271 } 4272 4273 // Fold remainder of division by a constant. 4274 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4275 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4276 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4277 4278 // When division is cheap or optimizing for minimum size, 4279 // fall through to DIVREM creation by skipping this fold. 4280 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) { 4281 if (N0.getOpcode() == ISD::UREM) { 4282 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4283 return Folded; 4284 } else if (N0.getOpcode() == ISD::SREM) { 4285 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4286 return Folded; 4287 } 4288 } 4289 } 4290 4291 // Fold away ALL boolean setcc's. 4292 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4293 SDValue Temp; 4294 switch (Cond) { 4295 default: llvm_unreachable("Unknown integer setcc!"); 4296 case ISD::SETEQ: // X == Y -> ~(X^Y) 4297 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4298 N0 = DAG.getNOT(dl, Temp, OpVT); 4299 if (!DCI.isCalledByLegalizer()) 4300 DCI.AddToWorklist(Temp.getNode()); 4301 break; 4302 case ISD::SETNE: // X != Y --> (X^Y) 4303 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4304 break; 4305 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4306 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4307 Temp = DAG.getNOT(dl, N0, OpVT); 4308 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4309 if (!DCI.isCalledByLegalizer()) 4310 DCI.AddToWorklist(Temp.getNode()); 4311 break; 4312 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4313 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4314 Temp = DAG.getNOT(dl, N1, OpVT); 4315 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4316 if (!DCI.isCalledByLegalizer()) 4317 DCI.AddToWorklist(Temp.getNode()); 4318 break; 4319 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4320 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4321 Temp = DAG.getNOT(dl, N0, OpVT); 4322 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4323 if (!DCI.isCalledByLegalizer()) 4324 DCI.AddToWorklist(Temp.getNode()); 4325 break; 4326 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4327 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4328 Temp = DAG.getNOT(dl, N1, OpVT); 4329 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4330 break; 4331 } 4332 if (VT.getScalarType() != MVT::i1) { 4333 if (!DCI.isCalledByLegalizer()) 4334 DCI.AddToWorklist(N0.getNode()); 4335 // FIXME: If running after legalize, we probably can't do this. 4336 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4337 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4338 } 4339 return N0; 4340 } 4341 4342 // Could not fold it. 4343 return SDValue(); 4344 } 4345 4346 /// Returns true (and the GlobalValue and the offset) if the node is a 4347 /// GlobalAddress + offset. 4348 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4349 int64_t &Offset) const { 4350 4351 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4352 4353 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4354 GA = GASD->getGlobal(); 4355 Offset += GASD->getOffset(); 4356 return true; 4357 } 4358 4359 if (N->getOpcode() == ISD::ADD) { 4360 SDValue N1 = N->getOperand(0); 4361 SDValue N2 = N->getOperand(1); 4362 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4363 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4364 Offset += V->getSExtValue(); 4365 return true; 4366 } 4367 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4368 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4369 Offset += V->getSExtValue(); 4370 return true; 4371 } 4372 } 4373 } 4374 4375 return false; 4376 } 4377 4378 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4379 DAGCombinerInfo &DCI) const { 4380 // Default implementation: no optimization. 4381 return SDValue(); 4382 } 4383 4384 //===----------------------------------------------------------------------===// 4385 // Inline Assembler Implementation Methods 4386 //===----------------------------------------------------------------------===// 4387 4388 TargetLowering::ConstraintType 4389 TargetLowering::getConstraintType(StringRef Constraint) const { 4390 unsigned S = Constraint.size(); 4391 4392 if (S == 1) { 4393 switch (Constraint[0]) { 4394 default: break; 4395 case 'r': 4396 return C_RegisterClass; 4397 case 'm': // memory 4398 case 'o': // offsetable 4399 case 'V': // not offsetable 4400 return C_Memory; 4401 case 'n': // Simple Integer 4402 case 'E': // Floating Point Constant 4403 case 'F': // Floating Point Constant 4404 return C_Immediate; 4405 case 'i': // Simple Integer or Relocatable Constant 4406 case 's': // Relocatable Constant 4407 case 'p': // Address. 4408 case 'X': // Allow ANY value. 4409 case 'I': // Target registers. 4410 case 'J': 4411 case 'K': 4412 case 'L': 4413 case 'M': 4414 case 'N': 4415 case 'O': 4416 case 'P': 4417 case '<': 4418 case '>': 4419 return C_Other; 4420 } 4421 } 4422 4423 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4424 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4425 return C_Memory; 4426 return C_Register; 4427 } 4428 return C_Unknown; 4429 } 4430 4431 /// Try to replace an X constraint, which matches anything, with another that 4432 /// has more specific requirements based on the type of the corresponding 4433 /// operand. 4434 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4435 if (ConstraintVT.isInteger()) 4436 return "r"; 4437 if (ConstraintVT.isFloatingPoint()) 4438 return "f"; // works for many targets 4439 return nullptr; 4440 } 4441 4442 SDValue TargetLowering::LowerAsmOutputForConstraint( 4443 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4444 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4445 return SDValue(); 4446 } 4447 4448 /// Lower the specified operand into the Ops vector. 4449 /// If it is invalid, don't add anything to Ops. 4450 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4451 std::string &Constraint, 4452 std::vector<SDValue> &Ops, 4453 SelectionDAG &DAG) const { 4454 4455 if (Constraint.length() > 1) return; 4456 4457 char ConstraintLetter = Constraint[0]; 4458 switch (ConstraintLetter) { 4459 default: break; 4460 case 'X': // Allows any operand; labels (basic block) use this. 4461 if (Op.getOpcode() == ISD::BasicBlock || 4462 Op.getOpcode() == ISD::TargetBlockAddress) { 4463 Ops.push_back(Op); 4464 return; 4465 } 4466 LLVM_FALLTHROUGH; 4467 case 'i': // Simple Integer or Relocatable Constant 4468 case 'n': // Simple Integer 4469 case 's': { // Relocatable Constant 4470 4471 GlobalAddressSDNode *GA; 4472 ConstantSDNode *C; 4473 BlockAddressSDNode *BA; 4474 uint64_t Offset = 0; 4475 4476 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 4477 // etc., since getelementpointer is variadic. We can't use 4478 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 4479 // while in this case the GA may be furthest from the root node which is 4480 // likely an ISD::ADD. 4481 while (1) { 4482 if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') { 4483 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 4484 GA->getValueType(0), 4485 Offset + GA->getOffset())); 4486 return; 4487 } else if ((C = dyn_cast<ConstantSDNode>(Op)) && 4488 ConstraintLetter != 's') { 4489 // gcc prints these as sign extended. Sign extend value to 64 bits 4490 // now; without this it would get ZExt'd later in 4491 // ScheduleDAGSDNodes::EmitNode, which is very generic. 4492 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 4493 BooleanContent BCont = getBooleanContents(MVT::i64); 4494 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont) 4495 : ISD::SIGN_EXTEND; 4496 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() 4497 : C->getSExtValue(); 4498 Ops.push_back(DAG.getTargetConstant(Offset + ExtVal, 4499 SDLoc(C), MVT::i64)); 4500 return; 4501 } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && 4502 ConstraintLetter != 'n') { 4503 Ops.push_back(DAG.getTargetBlockAddress( 4504 BA->getBlockAddress(), BA->getValueType(0), 4505 Offset + BA->getOffset(), BA->getTargetFlags())); 4506 return; 4507 } else { 4508 const unsigned OpCode = Op.getOpcode(); 4509 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 4510 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 4511 Op = Op.getOperand(1); 4512 // Subtraction is not commutative. 4513 else if (OpCode == ISD::ADD && 4514 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 4515 Op = Op.getOperand(0); 4516 else 4517 return; 4518 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 4519 continue; 4520 } 4521 } 4522 return; 4523 } 4524 break; 4525 } 4526 } 4527 } 4528 4529 std::pair<unsigned, const TargetRegisterClass *> 4530 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4531 StringRef Constraint, 4532 MVT VT) const { 4533 if (Constraint.empty() || Constraint[0] != '{') 4534 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4535 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4536 4537 // Remove the braces from around the name. 4538 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4539 4540 std::pair<unsigned, const TargetRegisterClass *> R = 4541 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4542 4543 // Figure out which register class contains this reg. 4544 for (const TargetRegisterClass *RC : RI->regclasses()) { 4545 // If none of the value types for this register class are valid, we 4546 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4547 if (!isLegalRC(*RI, *RC)) 4548 continue; 4549 4550 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 4551 I != E; ++I) { 4552 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 4553 std::pair<unsigned, const TargetRegisterClass *> S = 4554 std::make_pair(*I, RC); 4555 4556 // If this register class has the requested value type, return it, 4557 // otherwise keep searching and return the first class found 4558 // if no other is found which explicitly has the requested type. 4559 if (RI->isTypeLegalForClass(*RC, VT)) 4560 return S; 4561 if (!R.second) 4562 R = S; 4563 } 4564 } 4565 } 4566 4567 return R; 4568 } 4569 4570 //===----------------------------------------------------------------------===// 4571 // Constraint Selection. 4572 4573 /// Return true of this is an input operand that is a matching constraint like 4574 /// "4". 4575 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4576 assert(!ConstraintCode.empty() && "No known constraint!"); 4577 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4578 } 4579 4580 /// If this is an input matching constraint, this method returns the output 4581 /// operand it matches. 4582 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 4583 assert(!ConstraintCode.empty() && "No known constraint!"); 4584 return atoi(ConstraintCode.c_str()); 4585 } 4586 4587 /// Split up the constraint string from the inline assembly value into the 4588 /// specific constraints and their prefixes, and also tie in the associated 4589 /// operand values. 4590 /// If this returns an empty vector, and if the constraint string itself 4591 /// isn't empty, there was an error parsing. 4592 TargetLowering::AsmOperandInfoVector 4593 TargetLowering::ParseConstraints(const DataLayout &DL, 4594 const TargetRegisterInfo *TRI, 4595 const CallBase &Call) const { 4596 /// Information about all of the constraints. 4597 AsmOperandInfoVector ConstraintOperands; 4598 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 4599 unsigned maCount = 0; // Largest number of multiple alternative constraints. 4600 4601 // Do a prepass over the constraints, canonicalizing them, and building up the 4602 // ConstraintOperands list. 4603 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 4604 unsigned ResNo = 0; // ResNo - The result number of the next output. 4605 4606 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4607 ConstraintOperands.emplace_back(std::move(CI)); 4608 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 4609 4610 // Update multiple alternative constraint count. 4611 if (OpInfo.multipleAlternatives.size() > maCount) 4612 maCount = OpInfo.multipleAlternatives.size(); 4613 4614 OpInfo.ConstraintVT = MVT::Other; 4615 4616 // Compute the value type for each operand. 4617 switch (OpInfo.Type) { 4618 case InlineAsm::isOutput: 4619 // Indirect outputs just consume an argument. 4620 if (OpInfo.isIndirect) { 4621 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4622 break; 4623 } 4624 4625 // The return value of the call is this value. As such, there is no 4626 // corresponding argument. 4627 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 4628 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 4629 OpInfo.ConstraintVT = 4630 getSimpleValueType(DL, STy->getElementType(ResNo)); 4631 } else { 4632 assert(ResNo == 0 && "Asm only has one result!"); 4633 OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType()); 4634 } 4635 ++ResNo; 4636 break; 4637 case InlineAsm::isInput: 4638 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4639 break; 4640 case InlineAsm::isClobber: 4641 // Nothing to do. 4642 break; 4643 } 4644 4645 if (OpInfo.CallOperandVal) { 4646 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 4647 if (OpInfo.isIndirect) { 4648 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 4649 if (!PtrTy) 4650 report_fatal_error("Indirect operand for inline asm not a pointer!"); 4651 OpTy = PtrTy->getElementType(); 4652 } 4653 4654 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 4655 if (StructType *STy = dyn_cast<StructType>(OpTy)) 4656 if (STy->getNumElements() == 1) 4657 OpTy = STy->getElementType(0); 4658 4659 // If OpTy is not a single value, it may be a struct/union that we 4660 // can tile with integers. 4661 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4662 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 4663 switch (BitSize) { 4664 default: break; 4665 case 1: 4666 case 8: 4667 case 16: 4668 case 32: 4669 case 64: 4670 case 128: 4671 OpInfo.ConstraintVT = 4672 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 4673 break; 4674 } 4675 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 4676 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 4677 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 4678 } else { 4679 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 4680 } 4681 } 4682 } 4683 4684 // If we have multiple alternative constraints, select the best alternative. 4685 if (!ConstraintOperands.empty()) { 4686 if (maCount) { 4687 unsigned bestMAIndex = 0; 4688 int bestWeight = -1; 4689 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 4690 int weight = -1; 4691 unsigned maIndex; 4692 // Compute the sums of the weights for each alternative, keeping track 4693 // of the best (highest weight) one so far. 4694 for (maIndex = 0; maIndex < maCount; ++maIndex) { 4695 int weightSum = 0; 4696 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4697 cIndex != eIndex; ++cIndex) { 4698 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4699 if (OpInfo.Type == InlineAsm::isClobber) 4700 continue; 4701 4702 // If this is an output operand with a matching input operand, 4703 // look up the matching input. If their types mismatch, e.g. one 4704 // is an integer, the other is floating point, or their sizes are 4705 // different, flag it as an maCantMatch. 4706 if (OpInfo.hasMatchingInput()) { 4707 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4708 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4709 if ((OpInfo.ConstraintVT.isInteger() != 4710 Input.ConstraintVT.isInteger()) || 4711 (OpInfo.ConstraintVT.getSizeInBits() != 4712 Input.ConstraintVT.getSizeInBits())) { 4713 weightSum = -1; // Can't match. 4714 break; 4715 } 4716 } 4717 } 4718 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 4719 if (weight == -1) { 4720 weightSum = -1; 4721 break; 4722 } 4723 weightSum += weight; 4724 } 4725 // Update best. 4726 if (weightSum > bestWeight) { 4727 bestWeight = weightSum; 4728 bestMAIndex = maIndex; 4729 } 4730 } 4731 4732 // Now select chosen alternative in each constraint. 4733 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4734 cIndex != eIndex; ++cIndex) { 4735 AsmOperandInfo &cInfo = ConstraintOperands[cIndex]; 4736 if (cInfo.Type == InlineAsm::isClobber) 4737 continue; 4738 cInfo.selectAlternative(bestMAIndex); 4739 } 4740 } 4741 } 4742 4743 // Check and hook up tied operands, choose constraint code to use. 4744 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4745 cIndex != eIndex; ++cIndex) { 4746 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4747 4748 // If this is an output operand with a matching input operand, look up the 4749 // matching input. If their types mismatch, e.g. one is an integer, the 4750 // other is floating point, or their sizes are different, flag it as an 4751 // error. 4752 if (OpInfo.hasMatchingInput()) { 4753 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4754 4755 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4756 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 4757 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 4758 OpInfo.ConstraintVT); 4759 std::pair<unsigned, const TargetRegisterClass *> InputRC = 4760 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 4761 Input.ConstraintVT); 4762 if ((OpInfo.ConstraintVT.isInteger() != 4763 Input.ConstraintVT.isInteger()) || 4764 (MatchRC.second != InputRC.second)) { 4765 report_fatal_error("Unsupported asm: input constraint" 4766 " with a matching output constraint of" 4767 " incompatible type!"); 4768 } 4769 } 4770 } 4771 } 4772 4773 return ConstraintOperands; 4774 } 4775 4776 /// Return an integer indicating how general CT is. 4777 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 4778 switch (CT) { 4779 case TargetLowering::C_Immediate: 4780 case TargetLowering::C_Other: 4781 case TargetLowering::C_Unknown: 4782 return 0; 4783 case TargetLowering::C_Register: 4784 return 1; 4785 case TargetLowering::C_RegisterClass: 4786 return 2; 4787 case TargetLowering::C_Memory: 4788 return 3; 4789 } 4790 llvm_unreachable("Invalid constraint type"); 4791 } 4792 4793 /// Examine constraint type and operand type and determine a weight value. 4794 /// This object must already have been set up with the operand type 4795 /// and the current alternative constraint selected. 4796 TargetLowering::ConstraintWeight 4797 TargetLowering::getMultipleConstraintMatchWeight( 4798 AsmOperandInfo &info, int maIndex) const { 4799 InlineAsm::ConstraintCodeVector *rCodes; 4800 if (maIndex >= (int)info.multipleAlternatives.size()) 4801 rCodes = &info.Codes; 4802 else 4803 rCodes = &info.multipleAlternatives[maIndex].Codes; 4804 ConstraintWeight BestWeight = CW_Invalid; 4805 4806 // Loop over the options, keeping track of the most general one. 4807 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 4808 ConstraintWeight weight = 4809 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 4810 if (weight > BestWeight) 4811 BestWeight = weight; 4812 } 4813 4814 return BestWeight; 4815 } 4816 4817 /// Examine constraint type and operand type and determine a weight value. 4818 /// This object must already have been set up with the operand type 4819 /// and the current alternative constraint selected. 4820 TargetLowering::ConstraintWeight 4821 TargetLowering::getSingleConstraintMatchWeight( 4822 AsmOperandInfo &info, const char *constraint) const { 4823 ConstraintWeight weight = CW_Invalid; 4824 Value *CallOperandVal = info.CallOperandVal; 4825 // If we don't have a value, we can't do a match, 4826 // but allow it at the lowest weight. 4827 if (!CallOperandVal) 4828 return CW_Default; 4829 // Look at the constraint type. 4830 switch (*constraint) { 4831 case 'i': // immediate integer. 4832 case 'n': // immediate integer with a known value. 4833 if (isa<ConstantInt>(CallOperandVal)) 4834 weight = CW_Constant; 4835 break; 4836 case 's': // non-explicit intregal immediate. 4837 if (isa<GlobalValue>(CallOperandVal)) 4838 weight = CW_Constant; 4839 break; 4840 case 'E': // immediate float if host format. 4841 case 'F': // immediate float. 4842 if (isa<ConstantFP>(CallOperandVal)) 4843 weight = CW_Constant; 4844 break; 4845 case '<': // memory operand with autodecrement. 4846 case '>': // memory operand with autoincrement. 4847 case 'm': // memory operand. 4848 case 'o': // offsettable memory operand 4849 case 'V': // non-offsettable memory operand 4850 weight = CW_Memory; 4851 break; 4852 case 'r': // general register. 4853 case 'g': // general register, memory operand or immediate integer. 4854 // note: Clang converts "g" to "imr". 4855 if (CallOperandVal->getType()->isIntegerTy()) 4856 weight = CW_Register; 4857 break; 4858 case 'X': // any operand. 4859 default: 4860 weight = CW_Default; 4861 break; 4862 } 4863 return weight; 4864 } 4865 4866 /// If there are multiple different constraints that we could pick for this 4867 /// operand (e.g. "imr") try to pick the 'best' one. 4868 /// This is somewhat tricky: constraints fall into four classes: 4869 /// Other -> immediates and magic values 4870 /// Register -> one specific register 4871 /// RegisterClass -> a group of regs 4872 /// Memory -> memory 4873 /// Ideally, we would pick the most specific constraint possible: if we have 4874 /// something that fits into a register, we would pick it. The problem here 4875 /// is that if we have something that could either be in a register or in 4876 /// memory that use of the register could cause selection of *other* 4877 /// operands to fail: they might only succeed if we pick memory. Because of 4878 /// this the heuristic we use is: 4879 /// 4880 /// 1) If there is an 'other' constraint, and if the operand is valid for 4881 /// that constraint, use it. This makes us take advantage of 'i' 4882 /// constraints when available. 4883 /// 2) Otherwise, pick the most general constraint present. This prefers 4884 /// 'm' over 'r', for example. 4885 /// 4886 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 4887 const TargetLowering &TLI, 4888 SDValue Op, SelectionDAG *DAG) { 4889 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 4890 unsigned BestIdx = 0; 4891 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 4892 int BestGenerality = -1; 4893 4894 // Loop over the options, keeping track of the most general one. 4895 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 4896 TargetLowering::ConstraintType CType = 4897 TLI.getConstraintType(OpInfo.Codes[i]); 4898 4899 // Indirect 'other' or 'immediate' constraints are not allowed. 4900 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 4901 CType == TargetLowering::C_Register || 4902 CType == TargetLowering::C_RegisterClass)) 4903 continue; 4904 4905 // If this is an 'other' or 'immediate' constraint, see if the operand is 4906 // valid for it. For example, on X86 we might have an 'rI' constraint. If 4907 // the operand is an integer in the range [0..31] we want to use I (saving a 4908 // load of a register), otherwise we must use 'r'. 4909 if ((CType == TargetLowering::C_Other || 4910 CType == TargetLowering::C_Immediate) && Op.getNode()) { 4911 assert(OpInfo.Codes[i].size() == 1 && 4912 "Unhandled multi-letter 'other' constraint"); 4913 std::vector<SDValue> ResultOps; 4914 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 4915 ResultOps, *DAG); 4916 if (!ResultOps.empty()) { 4917 BestType = CType; 4918 BestIdx = i; 4919 break; 4920 } 4921 } 4922 4923 // Things with matching constraints can only be registers, per gcc 4924 // documentation. This mainly affects "g" constraints. 4925 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 4926 continue; 4927 4928 // This constraint letter is more general than the previous one, use it. 4929 int Generality = getConstraintGenerality(CType); 4930 if (Generality > BestGenerality) { 4931 BestType = CType; 4932 BestIdx = i; 4933 BestGenerality = Generality; 4934 } 4935 } 4936 4937 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 4938 OpInfo.ConstraintType = BestType; 4939 } 4940 4941 /// Determines the constraint code and constraint type to use for the specific 4942 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 4943 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 4944 SDValue Op, 4945 SelectionDAG *DAG) const { 4946 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 4947 4948 // Single-letter constraints ('r') are very common. 4949 if (OpInfo.Codes.size() == 1) { 4950 OpInfo.ConstraintCode = OpInfo.Codes[0]; 4951 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4952 } else { 4953 ChooseConstraint(OpInfo, *this, Op, DAG); 4954 } 4955 4956 // 'X' matches anything. 4957 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 4958 // Labels and constants are handled elsewhere ('X' is the only thing 4959 // that matches labels). For Functions, the type here is the type of 4960 // the result, which is not what we want to look at; leave them alone. 4961 Value *v = OpInfo.CallOperandVal; 4962 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 4963 OpInfo.CallOperandVal = v; 4964 return; 4965 } 4966 4967 if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress) 4968 return; 4969 4970 // Otherwise, try to resolve it to something we know about by looking at 4971 // the actual operand type. 4972 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 4973 OpInfo.ConstraintCode = Repl; 4974 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4975 } 4976 } 4977 } 4978 4979 /// Given an exact SDIV by a constant, create a multiplication 4980 /// with the multiplicative inverse of the constant. 4981 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 4982 const SDLoc &dl, SelectionDAG &DAG, 4983 SmallVectorImpl<SDNode *> &Created) { 4984 SDValue Op0 = N->getOperand(0); 4985 SDValue Op1 = N->getOperand(1); 4986 EVT VT = N->getValueType(0); 4987 EVT SVT = VT.getScalarType(); 4988 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 4989 EVT ShSVT = ShVT.getScalarType(); 4990 4991 bool UseSRA = false; 4992 SmallVector<SDValue, 16> Shifts, Factors; 4993 4994 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 4995 if (C->isNullValue()) 4996 return false; 4997 APInt Divisor = C->getAPIntValue(); 4998 unsigned Shift = Divisor.countTrailingZeros(); 4999 if (Shift) { 5000 Divisor.ashrInPlace(Shift); 5001 UseSRA = true; 5002 } 5003 // Calculate the multiplicative inverse, using Newton's method. 5004 APInt t; 5005 APInt Factor = Divisor; 5006 while ((t = Divisor * Factor) != 1) 5007 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5008 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5009 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5010 return true; 5011 }; 5012 5013 // Collect all magic values from the build vector. 5014 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5015 return SDValue(); 5016 5017 SDValue Shift, Factor; 5018 if (VT.isVector()) { 5019 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5020 Factor = DAG.getBuildVector(VT, dl, Factors); 5021 } else { 5022 Shift = Shifts[0]; 5023 Factor = Factors[0]; 5024 } 5025 5026 SDValue Res = Op0; 5027 5028 // Shift the value upfront if it is even, so the LSB is one. 5029 if (UseSRA) { 5030 // TODO: For UDIV use SRL instead of SRA. 5031 SDNodeFlags Flags; 5032 Flags.setExact(true); 5033 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5034 Created.push_back(Res.getNode()); 5035 } 5036 5037 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5038 } 5039 5040 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5041 SelectionDAG &DAG, 5042 SmallVectorImpl<SDNode *> &Created) const { 5043 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5044 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5045 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5046 return SDValue(N, 0); // Lower SDIV as SDIV 5047 return SDValue(); 5048 } 5049 5050 /// Given an ISD::SDIV node expressing a divide by constant, 5051 /// return a DAG expression to select that will generate the same value by 5052 /// multiplying by a magic number. 5053 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5054 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5055 bool IsAfterLegalization, 5056 SmallVectorImpl<SDNode *> &Created) const { 5057 SDLoc dl(N); 5058 EVT VT = N->getValueType(0); 5059 EVT SVT = VT.getScalarType(); 5060 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5061 EVT ShSVT = ShVT.getScalarType(); 5062 unsigned EltBits = VT.getScalarSizeInBits(); 5063 5064 // Check to see if we can do this. 5065 // FIXME: We should be more aggressive here. 5066 if (!isTypeLegal(VT)) 5067 return SDValue(); 5068 5069 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5070 if (N->getFlags().hasExact()) 5071 return BuildExactSDIV(*this, N, dl, DAG, Created); 5072 5073 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5074 5075 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5076 if (C->isNullValue()) 5077 return false; 5078 5079 const APInt &Divisor = C->getAPIntValue(); 5080 APInt::ms magics = Divisor.magic(); 5081 int NumeratorFactor = 0; 5082 int ShiftMask = -1; 5083 5084 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 5085 // If d is +1/-1, we just multiply the numerator by +1/-1. 5086 NumeratorFactor = Divisor.getSExtValue(); 5087 magics.m = 0; 5088 magics.s = 0; 5089 ShiftMask = 0; 5090 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 5091 // If d > 0 and m < 0, add the numerator. 5092 NumeratorFactor = 1; 5093 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 5094 // If d < 0 and m > 0, subtract the numerator. 5095 NumeratorFactor = -1; 5096 } 5097 5098 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 5099 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5100 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 5101 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5102 return true; 5103 }; 5104 5105 SDValue N0 = N->getOperand(0); 5106 SDValue N1 = N->getOperand(1); 5107 5108 // Collect the shifts / magic values from each element. 5109 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5110 return SDValue(); 5111 5112 SDValue MagicFactor, Factor, Shift, ShiftMask; 5113 if (VT.isVector()) { 5114 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5115 Factor = DAG.getBuildVector(VT, dl, Factors); 5116 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5117 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5118 } else { 5119 MagicFactor = MagicFactors[0]; 5120 Factor = Factors[0]; 5121 Shift = Shifts[0]; 5122 ShiftMask = ShiftMasks[0]; 5123 } 5124 5125 // Multiply the numerator (operand 0) by the magic value. 5126 // FIXME: We should support doing a MUL in a wider type. 5127 SDValue Q; 5128 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) 5129 : isOperationLegalOrCustom(ISD::MULHS, VT)) 5130 Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor); 5131 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) 5132 : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) { 5133 SDValue LoHi = 5134 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor); 5135 Q = SDValue(LoHi.getNode(), 1); 5136 } else 5137 return SDValue(); // No mulhs or equivalent. 5138 Created.push_back(Q.getNode()); 5139 5140 // (Optionally) Add/subtract the numerator using Factor. 5141 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5142 Created.push_back(Factor.getNode()); 5143 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5144 Created.push_back(Q.getNode()); 5145 5146 // Shift right algebraic by shift value. 5147 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5148 Created.push_back(Q.getNode()); 5149 5150 // Extract the sign bit, mask it and add it to the quotient. 5151 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5152 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5153 Created.push_back(T.getNode()); 5154 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5155 Created.push_back(T.getNode()); 5156 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5157 } 5158 5159 /// Given an ISD::UDIV node expressing a divide by constant, 5160 /// return a DAG expression to select that will generate the same value by 5161 /// multiplying by a magic number. 5162 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5163 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5164 bool IsAfterLegalization, 5165 SmallVectorImpl<SDNode *> &Created) const { 5166 SDLoc dl(N); 5167 EVT VT = N->getValueType(0); 5168 EVT SVT = VT.getScalarType(); 5169 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5170 EVT ShSVT = ShVT.getScalarType(); 5171 unsigned EltBits = VT.getScalarSizeInBits(); 5172 5173 // Check to see if we can do this. 5174 // FIXME: We should be more aggressive here. 5175 if (!isTypeLegal(VT)) 5176 return SDValue(); 5177 5178 bool UseNPQ = false; 5179 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5180 5181 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5182 if (C->isNullValue()) 5183 return false; 5184 // FIXME: We should use a narrower constant when the upper 5185 // bits are known to be zero. 5186 APInt Divisor = C->getAPIntValue(); 5187 APInt::mu magics = Divisor.magicu(); 5188 unsigned PreShift = 0, PostShift = 0; 5189 5190 // If the divisor is even, we can avoid using the expensive fixup by 5191 // shifting the divided value upfront. 5192 if (magics.a != 0 && !Divisor[0]) { 5193 PreShift = Divisor.countTrailingZeros(); 5194 // Get magic number for the shifted divisor. 5195 magics = Divisor.lshr(PreShift).magicu(PreShift); 5196 assert(magics.a == 0 && "Should use cheap fixup now"); 5197 } 5198 5199 APInt Magic = magics.m; 5200 5201 unsigned SelNPQ; 5202 if (magics.a == 0 || Divisor.isOneValue()) { 5203 assert(magics.s < Divisor.getBitWidth() && 5204 "We shouldn't generate an undefined shift!"); 5205 PostShift = magics.s; 5206 SelNPQ = false; 5207 } else { 5208 PostShift = magics.s - 1; 5209 SelNPQ = true; 5210 } 5211 5212 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5213 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5214 NPQFactors.push_back( 5215 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5216 : APInt::getNullValue(EltBits), 5217 dl, SVT)); 5218 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5219 UseNPQ |= SelNPQ; 5220 return true; 5221 }; 5222 5223 SDValue N0 = N->getOperand(0); 5224 SDValue N1 = N->getOperand(1); 5225 5226 // Collect the shifts/magic values from each element. 5227 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5228 return SDValue(); 5229 5230 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5231 if (VT.isVector()) { 5232 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5233 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5234 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5235 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5236 } else { 5237 PreShift = PreShifts[0]; 5238 MagicFactor = MagicFactors[0]; 5239 PostShift = PostShifts[0]; 5240 } 5241 5242 SDValue Q = N0; 5243 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5244 Created.push_back(Q.getNode()); 5245 5246 // FIXME: We should support doing a MUL in a wider type. 5247 auto GetMULHU = [&](SDValue X, SDValue Y) { 5248 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) 5249 : isOperationLegalOrCustom(ISD::MULHU, VT)) 5250 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5251 if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) 5252 : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) { 5253 SDValue LoHi = 5254 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5255 return SDValue(LoHi.getNode(), 1); 5256 } 5257 return SDValue(); // No mulhu or equivalent 5258 }; 5259 5260 // Multiply the numerator (operand 0) by the magic value. 5261 Q = GetMULHU(Q, MagicFactor); 5262 if (!Q) 5263 return SDValue(); 5264 5265 Created.push_back(Q.getNode()); 5266 5267 if (UseNPQ) { 5268 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5269 Created.push_back(NPQ.getNode()); 5270 5271 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5272 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5273 if (VT.isVector()) 5274 NPQ = GetMULHU(NPQ, NPQFactor); 5275 else 5276 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5277 5278 Created.push_back(NPQ.getNode()); 5279 5280 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5281 Created.push_back(Q.getNode()); 5282 } 5283 5284 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5285 Created.push_back(Q.getNode()); 5286 5287 SDValue One = DAG.getConstant(1, dl, VT); 5288 SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ); 5289 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5290 } 5291 5292 /// If all values in Values that *don't* match the predicate are same 'splat' 5293 /// value, then replace all values with that splat value. 5294 /// Else, if AlternativeReplacement was provided, then replace all values that 5295 /// do match predicate with AlternativeReplacement value. 5296 static void 5297 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5298 std::function<bool(SDValue)> Predicate, 5299 SDValue AlternativeReplacement = SDValue()) { 5300 SDValue Replacement; 5301 // Is there a value for which the Predicate does *NOT* match? What is it? 5302 auto SplatValue = llvm::find_if_not(Values, Predicate); 5303 if (SplatValue != Values.end()) { 5304 // Does Values consist only of SplatValue's and values matching Predicate? 5305 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5306 return Value == *SplatValue || Predicate(Value); 5307 })) // Then we shall replace values matching predicate with SplatValue. 5308 Replacement = *SplatValue; 5309 } 5310 if (!Replacement) { 5311 // Oops, we did not find the "baseline" splat value. 5312 if (!AlternativeReplacement) 5313 return; // Nothing to do. 5314 // Let's replace with provided value then. 5315 Replacement = AlternativeReplacement; 5316 } 5317 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5318 } 5319 5320 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5321 /// where the divisor is constant and the comparison target is zero, 5322 /// return a DAG expression that will generate the same comparison result 5323 /// using only multiplications, additions and shifts/rotations. 5324 /// Ref: "Hacker's Delight" 10-17. 5325 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5326 SDValue CompTargetNode, 5327 ISD::CondCode Cond, 5328 DAGCombinerInfo &DCI, 5329 const SDLoc &DL) const { 5330 SmallVector<SDNode *, 5> Built; 5331 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5332 DCI, DL, Built)) { 5333 for (SDNode *N : Built) 5334 DCI.AddToWorklist(N); 5335 return Folded; 5336 } 5337 5338 return SDValue(); 5339 } 5340 5341 SDValue 5342 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5343 SDValue CompTargetNode, ISD::CondCode Cond, 5344 DAGCombinerInfo &DCI, const SDLoc &DL, 5345 SmallVectorImpl<SDNode *> &Created) const { 5346 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5347 // - D must be constant, with D = D0 * 2^K where D0 is odd 5348 // - P is the multiplicative inverse of D0 modulo 2^W 5349 // - Q = floor(((2^W) - 1) / D) 5350 // where W is the width of the common type of N and D. 5351 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5352 "Only applicable for (in)equality comparisons."); 5353 5354 SelectionDAG &DAG = DCI.DAG; 5355 5356 EVT VT = REMNode.getValueType(); 5357 EVT SVT = VT.getScalarType(); 5358 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5359 EVT ShSVT = ShVT.getScalarType(); 5360 5361 // If MUL is unavailable, we cannot proceed in any case. 5362 if (!isOperationLegalOrCustom(ISD::MUL, VT)) 5363 return SDValue(); 5364 5365 bool ComparingWithAllZeros = true; 5366 bool AllComparisonsWithNonZerosAreTautological = true; 5367 bool HadTautologicalLanes = false; 5368 bool AllLanesAreTautological = true; 5369 bool HadEvenDivisor = false; 5370 bool AllDivisorsArePowerOfTwo = true; 5371 bool HadTautologicalInvertedLanes = false; 5372 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 5373 5374 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 5375 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5376 if (CDiv->isNullValue()) 5377 return false; 5378 5379 const APInt &D = CDiv->getAPIntValue(); 5380 const APInt &Cmp = CCmp->getAPIntValue(); 5381 5382 ComparingWithAllZeros &= Cmp.isNullValue(); 5383 5384 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5385 // if C2 is not less than C1, the comparison is always false. 5386 // But we will only be able to produce the comparison that will give the 5387 // opposive tautological answer. So this lane would need to be fixed up. 5388 bool TautologicalInvertedLane = D.ule(Cmp); 5389 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 5390 5391 // If all lanes are tautological (either all divisors are ones, or divisor 5392 // is not greater than the constant we are comparing with), 5393 // we will prefer to avoid the fold. 5394 bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane; 5395 HadTautologicalLanes |= TautologicalLane; 5396 AllLanesAreTautological &= TautologicalLane; 5397 5398 // If we are comparing with non-zero, we need'll need to subtract said 5399 // comparison value from the LHS. But there is no point in doing that if 5400 // every lane where we are comparing with non-zero is tautological.. 5401 if (!Cmp.isNullValue()) 5402 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 5403 5404 // Decompose D into D0 * 2^K 5405 unsigned K = D.countTrailingZeros(); 5406 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5407 APInt D0 = D.lshr(K); 5408 5409 // D is even if it has trailing zeros. 5410 HadEvenDivisor |= (K != 0); 5411 // D is a power-of-two if D0 is one. 5412 // If all divisors are power-of-two, we will prefer to avoid the fold. 5413 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5414 5415 // P = inv(D0, 2^W) 5416 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5417 unsigned W = D.getBitWidth(); 5418 APInt P = D0.zext(W + 1) 5419 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5420 .trunc(W); 5421 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5422 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5423 5424 // Q = floor((2^W - 1) u/ D) 5425 // R = ((2^W - 1) u% D) 5426 APInt Q, R; 5427 APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R); 5428 5429 // If we are comparing with zero, then that comparison constant is okay, 5430 // else it may need to be one less than that. 5431 if (Cmp.ugt(R)) 5432 Q -= 1; 5433 5434 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5435 "We are expecting that K is always less than all-ones for ShSVT"); 5436 5437 // If the lane is tautological the result can be constant-folded. 5438 if (TautologicalLane) { 5439 // Set P and K amount to a bogus values so we can try to splat them. 5440 P = 0; 5441 K = -1; 5442 // And ensure that comparison constant is tautological, 5443 // it will always compare true/false. 5444 Q = -1; 5445 } 5446 5447 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5448 KAmts.push_back( 5449 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5450 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5451 return true; 5452 }; 5453 5454 SDValue N = REMNode.getOperand(0); 5455 SDValue D = REMNode.getOperand(1); 5456 5457 // Collect the values from each element. 5458 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 5459 return SDValue(); 5460 5461 // If all lanes are tautological, the result can be constant-folded. 5462 if (AllLanesAreTautological) 5463 return SDValue(); 5464 5465 // If this is a urem by a powers-of-two, avoid the fold since it can be 5466 // best implemented as a bit test. 5467 if (AllDivisorsArePowerOfTwo) 5468 return SDValue(); 5469 5470 SDValue PVal, KVal, QVal; 5471 if (VT.isVector()) { 5472 if (HadTautologicalLanes) { 5473 // Try to turn PAmts into a splat, since we don't care about the values 5474 // that are currently '0'. If we can't, just keep '0'`s. 5475 turnVectorIntoSplatVector(PAmts, isNullConstant); 5476 // Try to turn KAmts into a splat, since we don't care about the values 5477 // that are currently '-1'. If we can't, change them to '0'`s. 5478 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5479 DAG.getConstant(0, DL, ShSVT)); 5480 } 5481 5482 PVal = DAG.getBuildVector(VT, DL, PAmts); 5483 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5484 QVal = DAG.getBuildVector(VT, DL, QAmts); 5485 } else { 5486 PVal = PAmts[0]; 5487 KVal = KAmts[0]; 5488 QVal = QAmts[0]; 5489 } 5490 5491 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 5492 if (!isOperationLegalOrCustom(ISD::SUB, VT)) 5493 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 5494 assert(CompTargetNode.getValueType() == N.getValueType() && 5495 "Expecting that the types on LHS and RHS of comparisons match."); 5496 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 5497 } 5498 5499 // (mul N, P) 5500 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5501 Created.push_back(Op0.getNode()); 5502 5503 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5504 // divisors as a performance improvement, since rotating by 0 is a no-op. 5505 if (HadEvenDivisor) { 5506 // We need ROTR to do this. 5507 if (!isOperationLegalOrCustom(ISD::ROTR, VT)) 5508 return SDValue(); 5509 SDNodeFlags Flags; 5510 Flags.setExact(true); 5511 // UREM: (rotr (mul N, P), K) 5512 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5513 Created.push_back(Op0.getNode()); 5514 } 5515 5516 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 5517 SDValue NewCC = 5518 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5519 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5520 if (!HadTautologicalInvertedLanes) 5521 return NewCC; 5522 5523 // If any lanes previously compared always-false, the NewCC will give 5524 // always-true result for them, so we need to fixup those lanes. 5525 // Or the other way around for inequality predicate. 5526 assert(VT.isVector() && "Can/should only get here for vectors."); 5527 Created.push_back(NewCC.getNode()); 5528 5529 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5530 // if C2 is not less than C1, the comparison is always false. 5531 // But we have produced the comparison that will give the 5532 // opposive tautological answer. So these lanes would need to be fixed up. 5533 SDValue TautologicalInvertedChannels = 5534 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 5535 Created.push_back(TautologicalInvertedChannels.getNode()); 5536 5537 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 5538 // If we have a vector select, let's replace the comparison results in the 5539 // affected lanes with the correct tautological result. 5540 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 5541 DL, SETCCVT, SETCCVT); 5542 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 5543 Replacement, NewCC); 5544 } 5545 5546 // Else, we can just invert the comparison result in the appropriate lanes. 5547 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 5548 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 5549 TautologicalInvertedChannels); 5550 5551 return SDValue(); // Don't know how to lower. 5552 } 5553 5554 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 5555 /// where the divisor is constant and the comparison target is zero, 5556 /// return a DAG expression that will generate the same comparison result 5557 /// using only multiplications, additions and shifts/rotations. 5558 /// Ref: "Hacker's Delight" 10-17. 5559 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 5560 SDValue CompTargetNode, 5561 ISD::CondCode Cond, 5562 DAGCombinerInfo &DCI, 5563 const SDLoc &DL) const { 5564 SmallVector<SDNode *, 7> Built; 5565 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5566 DCI, DL, Built)) { 5567 assert(Built.size() <= 7 && "Max size prediction failed."); 5568 for (SDNode *N : Built) 5569 DCI.AddToWorklist(N); 5570 return Folded; 5571 } 5572 5573 return SDValue(); 5574 } 5575 5576 SDValue 5577 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 5578 SDValue CompTargetNode, ISD::CondCode Cond, 5579 DAGCombinerInfo &DCI, const SDLoc &DL, 5580 SmallVectorImpl<SDNode *> &Created) const { 5581 // Fold: 5582 // (seteq/ne (srem N, D), 0) 5583 // To: 5584 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 5585 // 5586 // - D must be constant, with D = D0 * 2^K where D0 is odd 5587 // - P is the multiplicative inverse of D0 modulo 2^W 5588 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 5589 // - Q = floor((2 * A) / (2^K)) 5590 // where W is the width of the common type of N and D. 5591 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5592 "Only applicable for (in)equality comparisons."); 5593 5594 SelectionDAG &DAG = DCI.DAG; 5595 5596 EVT VT = REMNode.getValueType(); 5597 EVT SVT = VT.getScalarType(); 5598 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5599 EVT ShSVT = ShVT.getScalarType(); 5600 5601 // If MUL is unavailable, we cannot proceed in any case. 5602 if (!isOperationLegalOrCustom(ISD::MUL, VT)) 5603 return SDValue(); 5604 5605 // TODO: Could support comparing with non-zero too. 5606 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 5607 if (!CompTarget || !CompTarget->isNullValue()) 5608 return SDValue(); 5609 5610 bool HadIntMinDivisor = false; 5611 bool HadOneDivisor = false; 5612 bool AllDivisorsAreOnes = true; 5613 bool HadEvenDivisor = false; 5614 bool NeedToApplyOffset = false; 5615 bool AllDivisorsArePowerOfTwo = true; 5616 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 5617 5618 auto BuildSREMPattern = [&](ConstantSDNode *C) { 5619 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5620 if (C->isNullValue()) 5621 return false; 5622 5623 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 5624 5625 // WARNING: this fold is only valid for positive divisors! 5626 APInt D = C->getAPIntValue(); 5627 if (D.isNegative()) 5628 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 5629 5630 HadIntMinDivisor |= D.isMinSignedValue(); 5631 5632 // If all divisors are ones, we will prefer to avoid the fold. 5633 HadOneDivisor |= D.isOneValue(); 5634 AllDivisorsAreOnes &= D.isOneValue(); 5635 5636 // Decompose D into D0 * 2^K 5637 unsigned K = D.countTrailingZeros(); 5638 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5639 APInt D0 = D.lshr(K); 5640 5641 if (!D.isMinSignedValue()) { 5642 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 5643 // we don't care about this lane in this fold, we'll special-handle it. 5644 HadEvenDivisor |= (K != 0); 5645 } 5646 5647 // D is a power-of-two if D0 is one. This includes INT_MIN. 5648 // If all divisors are power-of-two, we will prefer to avoid the fold. 5649 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5650 5651 // P = inv(D0, 2^W) 5652 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5653 unsigned W = D.getBitWidth(); 5654 APInt P = D0.zext(W + 1) 5655 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5656 .trunc(W); 5657 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5658 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5659 5660 // A = floor((2^(W - 1) - 1) / D0) & -2^K 5661 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 5662 A.clearLowBits(K); 5663 5664 if (!D.isMinSignedValue()) { 5665 // If divisor INT_MIN, then we don't care about this lane in this fold, 5666 // we'll special-handle it. 5667 NeedToApplyOffset |= A != 0; 5668 } 5669 5670 // Q = floor((2 * A) / (2^K)) 5671 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 5672 5673 assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) && 5674 "We are expecting that A is always less than all-ones for SVT"); 5675 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5676 "We are expecting that K is always less than all-ones for ShSVT"); 5677 5678 // If the divisor is 1 the result can be constant-folded. Likewise, we 5679 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 5680 if (D.isOneValue()) { 5681 // Set P, A and K to a bogus values so we can try to splat them. 5682 P = 0; 5683 A = -1; 5684 K = -1; 5685 5686 // x ?% 1 == 0 <--> true <--> x u<= -1 5687 Q = -1; 5688 } 5689 5690 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5691 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 5692 KAmts.push_back( 5693 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5694 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5695 return true; 5696 }; 5697 5698 SDValue N = REMNode.getOperand(0); 5699 SDValue D = REMNode.getOperand(1); 5700 5701 // Collect the values from each element. 5702 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 5703 return SDValue(); 5704 5705 // If this is a srem by a one, avoid the fold since it can be constant-folded. 5706 if (AllDivisorsAreOnes) 5707 return SDValue(); 5708 5709 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 5710 // since it can be best implemented as a bit test. 5711 if (AllDivisorsArePowerOfTwo) 5712 return SDValue(); 5713 5714 SDValue PVal, AVal, KVal, QVal; 5715 if (VT.isVector()) { 5716 if (HadOneDivisor) { 5717 // Try to turn PAmts into a splat, since we don't care about the values 5718 // that are currently '0'. If we can't, just keep '0'`s. 5719 turnVectorIntoSplatVector(PAmts, isNullConstant); 5720 // Try to turn AAmts into a splat, since we don't care about the 5721 // values that are currently '-1'. If we can't, change them to '0'`s. 5722 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 5723 DAG.getConstant(0, DL, SVT)); 5724 // Try to turn KAmts into a splat, since we don't care about the values 5725 // that are currently '-1'. If we can't, change them to '0'`s. 5726 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5727 DAG.getConstant(0, DL, ShSVT)); 5728 } 5729 5730 PVal = DAG.getBuildVector(VT, DL, PAmts); 5731 AVal = DAG.getBuildVector(VT, DL, AAmts); 5732 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5733 QVal = DAG.getBuildVector(VT, DL, QAmts); 5734 } else { 5735 PVal = PAmts[0]; 5736 AVal = AAmts[0]; 5737 KVal = KAmts[0]; 5738 QVal = QAmts[0]; 5739 } 5740 5741 // (mul N, P) 5742 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5743 Created.push_back(Op0.getNode()); 5744 5745 if (NeedToApplyOffset) { 5746 // We need ADD to do this. 5747 if (!isOperationLegalOrCustom(ISD::ADD, VT)) 5748 return SDValue(); 5749 5750 // (add (mul N, P), A) 5751 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 5752 Created.push_back(Op0.getNode()); 5753 } 5754 5755 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5756 // divisors as a performance improvement, since rotating by 0 is a no-op. 5757 if (HadEvenDivisor) { 5758 // We need ROTR to do this. 5759 if (!isOperationLegalOrCustom(ISD::ROTR, VT)) 5760 return SDValue(); 5761 SDNodeFlags Flags; 5762 Flags.setExact(true); 5763 // SREM: (rotr (add (mul N, P), A), K) 5764 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5765 Created.push_back(Op0.getNode()); 5766 } 5767 5768 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 5769 SDValue Fold = 5770 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5771 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5772 5773 // If we didn't have lanes with INT_MIN divisor, then we're done. 5774 if (!HadIntMinDivisor) 5775 return Fold; 5776 5777 // That fold is only valid for positive divisors. Which effectively means, 5778 // it is invalid for INT_MIN divisors. So if we have such a lane, 5779 // we must fix-up results for said lanes. 5780 assert(VT.isVector() && "Can/should only get here for vectors."); 5781 5782 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 5783 !isOperationLegalOrCustom(ISD::AND, VT) || 5784 !isOperationLegalOrCustom(Cond, VT) || 5785 !isOperationLegalOrCustom(ISD::VSELECT, VT)) 5786 return SDValue(); 5787 5788 Created.push_back(Fold.getNode()); 5789 5790 SDValue IntMin = DAG.getConstant( 5791 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 5792 SDValue IntMax = DAG.getConstant( 5793 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 5794 SDValue Zero = 5795 DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT); 5796 5797 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 5798 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 5799 Created.push_back(DivisorIsIntMin.getNode()); 5800 5801 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 5802 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 5803 Created.push_back(Masked.getNode()); 5804 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 5805 Created.push_back(MaskedIsZero.getNode()); 5806 5807 // To produce final result we need to blend 2 vectors: 'SetCC' and 5808 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 5809 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 5810 // constant-folded, select can get lowered to a shuffle with constant mask. 5811 SDValue Blended = 5812 DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold); 5813 5814 return Blended; 5815 } 5816 5817 bool TargetLowering:: 5818 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 5819 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 5820 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 5821 "be a constant integer"); 5822 return true; 5823 } 5824 5825 return false; 5826 } 5827 5828 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 5829 bool LegalOps, bool OptForSize, 5830 NegatibleCost &Cost, 5831 unsigned Depth) const { 5832 // fneg is removable even if it has multiple uses. 5833 if (Op.getOpcode() == ISD::FNEG) { 5834 Cost = NegatibleCost::Cheaper; 5835 return Op.getOperand(0); 5836 } 5837 5838 // Don't recurse exponentially. 5839 if (Depth > SelectionDAG::MaxRecursionDepth) 5840 return SDValue(); 5841 5842 // Pre-increment recursion depth for use in recursive calls. 5843 ++Depth; 5844 const SDNodeFlags Flags = Op->getFlags(); 5845 const TargetOptions &Options = DAG.getTarget().Options; 5846 EVT VT = Op.getValueType(); 5847 unsigned Opcode = Op.getOpcode(); 5848 5849 // Don't allow anything with multiple uses unless we know it is free. 5850 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 5851 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 5852 isFPExtFree(VT, Op.getOperand(0).getValueType()); 5853 if (!IsFreeExtend) 5854 return SDValue(); 5855 } 5856 5857 auto RemoveDeadNode = [&](SDValue N) { 5858 if (N && N.getNode()->use_empty()) 5859 DAG.RemoveDeadNode(N.getNode()); 5860 }; 5861 5862 SDLoc DL(Op); 5863 5864 switch (Opcode) { 5865 case ISD::ConstantFP: { 5866 // Don't invert constant FP values after legalization unless the target says 5867 // the negated constant is legal. 5868 bool IsOpLegal = 5869 isOperationLegal(ISD::ConstantFP, VT) || 5870 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 5871 OptForSize); 5872 5873 if (LegalOps && !IsOpLegal) 5874 break; 5875 5876 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5877 V.changeSign(); 5878 SDValue CFP = DAG.getConstantFP(V, DL, VT); 5879 5880 // If we already have the use of the negated floating constant, it is free 5881 // to negate it even it has multiple uses. 5882 if (!Op.hasOneUse() && CFP.use_empty()) 5883 break; 5884 Cost = NegatibleCost::Neutral; 5885 return CFP; 5886 } 5887 case ISD::BUILD_VECTOR: { 5888 // Only permit BUILD_VECTOR of constants. 5889 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 5890 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 5891 })) 5892 break; 5893 5894 bool IsOpLegal = 5895 (isOperationLegal(ISD::ConstantFP, VT) && 5896 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 5897 llvm::all_of(Op->op_values(), [&](SDValue N) { 5898 return N.isUndef() || 5899 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 5900 OptForSize); 5901 }); 5902 5903 if (LegalOps && !IsOpLegal) 5904 break; 5905 5906 SmallVector<SDValue, 4> Ops; 5907 for (SDValue C : Op->op_values()) { 5908 if (C.isUndef()) { 5909 Ops.push_back(C); 5910 continue; 5911 } 5912 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 5913 V.changeSign(); 5914 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 5915 } 5916 Cost = NegatibleCost::Neutral; 5917 return DAG.getBuildVector(VT, DL, Ops); 5918 } 5919 case ISD::FADD: { 5920 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 5921 break; 5922 5923 // After operation legalization, it might not be legal to create new FSUBs. 5924 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 5925 break; 5926 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 5927 5928 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 5929 NegatibleCost CostX = NegatibleCost::Expensive; 5930 SDValue NegX = 5931 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 5932 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 5933 NegatibleCost CostY = NegatibleCost::Expensive; 5934 SDValue NegY = 5935 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 5936 5937 // Negate the X if its cost is less or equal than Y. 5938 if (NegX && (CostX <= CostY)) { 5939 Cost = CostX; 5940 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 5941 if (NegY != N) 5942 RemoveDeadNode(NegY); 5943 return N; 5944 } 5945 5946 // Negate the Y if it is not expensive. 5947 if (NegY) { 5948 Cost = CostY; 5949 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 5950 if (NegX != N) 5951 RemoveDeadNode(NegX); 5952 return N; 5953 } 5954 break; 5955 } 5956 case ISD::FSUB: { 5957 // We can't turn -(A-B) into B-A when we honor signed zeros. 5958 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 5959 break; 5960 5961 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 5962 // fold (fneg (fsub 0, Y)) -> Y 5963 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 5964 if (C->isZero()) { 5965 Cost = NegatibleCost::Cheaper; 5966 return Y; 5967 } 5968 5969 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 5970 Cost = NegatibleCost::Neutral; 5971 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 5972 } 5973 case ISD::FMUL: 5974 case ISD::FDIV: { 5975 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 5976 5977 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 5978 NegatibleCost CostX = NegatibleCost::Expensive; 5979 SDValue NegX = 5980 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 5981 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 5982 NegatibleCost CostY = NegatibleCost::Expensive; 5983 SDValue NegY = 5984 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 5985 5986 // Negate the X if its cost is less or equal than Y. 5987 if (NegX && (CostX <= CostY)) { 5988 Cost = CostX; 5989 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 5990 if (NegY != N) 5991 RemoveDeadNode(NegY); 5992 return N; 5993 } 5994 5995 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 5996 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 5997 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 5998 break; 5999 6000 // Negate the Y if it is not expensive. 6001 if (NegY) { 6002 Cost = CostY; 6003 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6004 if (NegX != N) 6005 RemoveDeadNode(NegX); 6006 return N; 6007 } 6008 break; 6009 } 6010 case ISD::FMA: 6011 case ISD::FMAD: { 6012 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6013 break; 6014 6015 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6016 NegatibleCost CostZ = NegatibleCost::Expensive; 6017 SDValue NegZ = 6018 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6019 // Give up if fail to negate the Z. 6020 if (!NegZ) 6021 break; 6022 6023 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6024 NegatibleCost CostX = NegatibleCost::Expensive; 6025 SDValue NegX = 6026 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6027 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6028 NegatibleCost CostY = NegatibleCost::Expensive; 6029 SDValue NegY = 6030 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6031 6032 // Negate the X if its cost is less or equal than Y. 6033 if (NegX && (CostX <= CostY)) { 6034 Cost = std::min(CostX, CostZ); 6035 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6036 if (NegY != N) 6037 RemoveDeadNode(NegY); 6038 return N; 6039 } 6040 6041 // Negate the Y if it is not expensive. 6042 if (NegY) { 6043 Cost = std::min(CostY, CostZ); 6044 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6045 if (NegX != N) 6046 RemoveDeadNode(NegX); 6047 return N; 6048 } 6049 break; 6050 } 6051 6052 case ISD::FP_EXTEND: 6053 case ISD::FSIN: 6054 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6055 OptForSize, Cost, Depth)) 6056 return DAG.getNode(Opcode, DL, VT, NegV); 6057 break; 6058 case ISD::FP_ROUND: 6059 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6060 OptForSize, Cost, Depth)) 6061 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6062 break; 6063 } 6064 6065 return SDValue(); 6066 } 6067 6068 //===----------------------------------------------------------------------===// 6069 // Legalization Utilities 6070 //===----------------------------------------------------------------------===// 6071 6072 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6073 SDValue LHS, SDValue RHS, 6074 SmallVectorImpl<SDValue> &Result, 6075 EVT HiLoVT, SelectionDAG &DAG, 6076 MulExpansionKind Kind, SDValue LL, 6077 SDValue LH, SDValue RL, SDValue RH) const { 6078 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6079 Opcode == ISD::SMUL_LOHI); 6080 6081 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6082 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6083 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6084 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6085 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6086 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6087 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6088 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6089 6090 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6091 return false; 6092 6093 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6094 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6095 6096 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6097 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6098 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6099 6100 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6101 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6102 bool Signed) -> bool { 6103 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6104 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6105 Hi = SDValue(Lo.getNode(), 1); 6106 return true; 6107 } 6108 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6109 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6110 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6111 return true; 6112 } 6113 return false; 6114 }; 6115 6116 SDValue Lo, Hi; 6117 6118 if (!LL.getNode() && !RL.getNode() && 6119 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6120 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6121 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6122 } 6123 6124 if (!LL.getNode()) 6125 return false; 6126 6127 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6128 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6129 DAG.MaskedValueIsZero(RHS, HighMask)) { 6130 // The inputs are both zero-extended. 6131 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6132 Result.push_back(Lo); 6133 Result.push_back(Hi); 6134 if (Opcode != ISD::MUL) { 6135 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6136 Result.push_back(Zero); 6137 Result.push_back(Zero); 6138 } 6139 return true; 6140 } 6141 } 6142 6143 if (!VT.isVector() && Opcode == ISD::MUL && 6144 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6145 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6146 // The input values are both sign-extended. 6147 // TODO non-MUL case? 6148 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6149 Result.push_back(Lo); 6150 Result.push_back(Hi); 6151 return true; 6152 } 6153 } 6154 6155 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6156 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6157 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 6158 // FIXME getShiftAmountTy does not always return a sensible result when VT 6159 // is an illegal type, and so the type may be too small to fit the shift 6160 // amount. Override it with i32. The shift will have to be legalized. 6161 ShiftAmountTy = MVT::i32; 6162 } 6163 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6164 6165 if (!LH.getNode() && !RH.getNode() && 6166 isOperationLegalOrCustom(ISD::SRL, VT) && 6167 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6168 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6169 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6170 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6171 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6172 } 6173 6174 if (!LH.getNode()) 6175 return false; 6176 6177 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6178 return false; 6179 6180 Result.push_back(Lo); 6181 6182 if (Opcode == ISD::MUL) { 6183 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6184 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6185 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6186 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6187 Result.push_back(Hi); 6188 return true; 6189 } 6190 6191 // Compute the full width result. 6192 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6193 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6194 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6195 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6196 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6197 }; 6198 6199 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6200 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6201 return false; 6202 6203 // This is effectively the add part of a multiply-add of half-sized operands, 6204 // so it cannot overflow. 6205 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6206 6207 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6208 return false; 6209 6210 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6211 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6212 6213 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6214 isOperationLegalOrCustom(ISD::ADDE, VT)); 6215 if (UseGlue) 6216 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6217 Merge(Lo, Hi)); 6218 else 6219 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6220 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6221 6222 SDValue Carry = Next.getValue(1); 6223 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6224 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6225 6226 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6227 return false; 6228 6229 if (UseGlue) 6230 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6231 Carry); 6232 else 6233 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6234 Zero, Carry); 6235 6236 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6237 6238 if (Opcode == ISD::SMUL_LOHI) { 6239 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6240 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6241 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6242 6243 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6244 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6245 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6246 } 6247 6248 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6249 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6250 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6251 return true; 6252 } 6253 6254 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6255 SelectionDAG &DAG, MulExpansionKind Kind, 6256 SDValue LL, SDValue LH, SDValue RL, 6257 SDValue RH) const { 6258 SmallVector<SDValue, 2> Result; 6259 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6260 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6261 DAG, Kind, LL, LH, RL, RH); 6262 if (Ok) { 6263 assert(Result.size() == 2); 6264 Lo = Result[0]; 6265 Hi = Result[1]; 6266 } 6267 return Ok; 6268 } 6269 6270 // Check that (every element of) Z is undef or not an exact multiple of BW. 6271 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6272 return ISD::matchUnaryPredicate( 6273 Z, 6274 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6275 true); 6276 } 6277 6278 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 6279 SelectionDAG &DAG) const { 6280 EVT VT = Node->getValueType(0); 6281 6282 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6283 !isOperationLegalOrCustom(ISD::SRL, VT) || 6284 !isOperationLegalOrCustom(ISD::SUB, VT) || 6285 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6286 return false; 6287 6288 SDValue X = Node->getOperand(0); 6289 SDValue Y = Node->getOperand(1); 6290 SDValue Z = Node->getOperand(2); 6291 6292 unsigned BW = VT.getScalarSizeInBits(); 6293 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6294 SDLoc DL(SDValue(Node, 0)); 6295 6296 EVT ShVT = Z.getValueType(); 6297 6298 // If a funnel shift in the other direction is more supported, use it. 6299 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6300 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6301 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6302 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6303 // fshl X, Y, Z -> fshr X, Y, -Z 6304 // fshr X, Y, Z -> fshl X, Y, -Z 6305 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6306 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 6307 } else { 6308 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 6309 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 6310 SDValue One = DAG.getConstant(1, DL, ShVT); 6311 if (IsFSHL) { 6312 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6313 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 6314 } else { 6315 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6316 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 6317 } 6318 Z = DAG.getNOT(DL, Z, ShVT); 6319 } 6320 Result = DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 6321 return true; 6322 } 6323 6324 SDValue ShX, ShY; 6325 SDValue ShAmt, InvShAmt; 6326 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6327 // fshl: X << C | Y >> (BW - C) 6328 // fshr: X << (BW - C) | Y >> C 6329 // where C = Z % BW is not zero 6330 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6331 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6332 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 6333 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 6334 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6335 } else { 6336 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 6337 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 6338 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 6339 if (isPowerOf2_32(BW)) { 6340 // Z % BW -> Z & (BW - 1) 6341 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 6342 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 6343 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 6344 } else { 6345 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6346 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6347 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 6348 } 6349 6350 SDValue One = DAG.getConstant(1, DL, ShVT); 6351 if (IsFSHL) { 6352 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 6353 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 6354 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 6355 } else { 6356 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 6357 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 6358 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 6359 } 6360 } 6361 Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 6362 return true; 6363 } 6364 6365 // TODO: Merge with expandFunnelShift. 6366 bool TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 6367 SDValue &Result, SelectionDAG &DAG) const { 6368 EVT VT = Node->getValueType(0); 6369 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6370 bool IsLeft = Node->getOpcode() == ISD::ROTL; 6371 SDValue Op0 = Node->getOperand(0); 6372 SDValue Op1 = Node->getOperand(1); 6373 SDLoc DL(SDValue(Node, 0)); 6374 6375 EVT ShVT = Op1.getValueType(); 6376 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6377 6378 // If a rotate in the other direction is supported, use it. 6379 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 6380 if (isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 6381 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6382 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 6383 return true; 6384 } 6385 6386 if (!AllowVectorOps && VT.isVector() && 6387 (!isOperationLegalOrCustom(ISD::SHL, VT) || 6388 !isOperationLegalOrCustom(ISD::SRL, VT) || 6389 !isOperationLegalOrCustom(ISD::SUB, VT) || 6390 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 6391 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6392 return false; 6393 6394 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 6395 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 6396 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 6397 SDValue ShVal; 6398 SDValue HsVal; 6399 if (isPowerOf2_32(EltSizeInBits)) { 6400 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 6401 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 6402 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6403 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 6404 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6405 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 6406 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 6407 } else { 6408 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 6409 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 6410 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 6411 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 6412 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6413 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 6414 SDValue One = DAG.getConstant(1, DL, ShVT); 6415 HsVal = 6416 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 6417 } 6418 Result = DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 6419 return true; 6420 } 6421 6422 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 6423 SelectionDAG &DAG) const { 6424 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6425 SDValue Src = Node->getOperand(OpNo); 6426 EVT SrcVT = Src.getValueType(); 6427 EVT DstVT = Node->getValueType(0); 6428 SDLoc dl(SDValue(Node, 0)); 6429 6430 // FIXME: Only f32 to i64 conversions are supported. 6431 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 6432 return false; 6433 6434 if (Node->isStrictFPOpcode()) 6435 // When a NaN is converted to an integer a trap is allowed. We can't 6436 // use this expansion here because it would eliminate that trap. Other 6437 // traps are also allowed and cannot be eliminated. See 6438 // IEEE 754-2008 sec 5.8. 6439 return false; 6440 6441 // Expand f32 -> i64 conversion 6442 // This algorithm comes from compiler-rt's implementation of fixsfdi: 6443 // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c 6444 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 6445 EVT IntVT = SrcVT.changeTypeToInteger(); 6446 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 6447 6448 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 6449 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 6450 SDValue Bias = DAG.getConstant(127, dl, IntVT); 6451 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 6452 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 6453 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 6454 6455 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 6456 6457 SDValue ExponentBits = DAG.getNode( 6458 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 6459 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 6460 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 6461 6462 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 6463 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 6464 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 6465 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 6466 6467 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 6468 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 6469 DAG.getConstant(0x00800000, dl, IntVT)); 6470 6471 R = DAG.getZExtOrTrunc(R, dl, DstVT); 6472 6473 R = DAG.getSelectCC( 6474 dl, Exponent, ExponentLoBit, 6475 DAG.getNode(ISD::SHL, dl, DstVT, R, 6476 DAG.getZExtOrTrunc( 6477 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 6478 dl, IntShVT)), 6479 DAG.getNode(ISD::SRL, dl, DstVT, R, 6480 DAG.getZExtOrTrunc( 6481 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 6482 dl, IntShVT)), 6483 ISD::SETGT); 6484 6485 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 6486 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 6487 6488 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 6489 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 6490 return true; 6491 } 6492 6493 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 6494 SDValue &Chain, 6495 SelectionDAG &DAG) const { 6496 SDLoc dl(SDValue(Node, 0)); 6497 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6498 SDValue Src = Node->getOperand(OpNo); 6499 6500 EVT SrcVT = Src.getValueType(); 6501 EVT DstVT = Node->getValueType(0); 6502 EVT SetCCVT = 6503 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 6504 EVT DstSetCCVT = 6505 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 6506 6507 // Only expand vector types if we have the appropriate vector bit operations. 6508 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 6509 ISD::FP_TO_SINT; 6510 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 6511 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 6512 return false; 6513 6514 // If the maximum float value is smaller then the signed integer range, 6515 // the destination signmask can't be represented by the float, so we can 6516 // just use FP_TO_SINT directly. 6517 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 6518 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 6519 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 6520 if (APFloat::opOverflow & 6521 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 6522 if (Node->isStrictFPOpcode()) { 6523 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6524 { Node->getOperand(0), Src }); 6525 Chain = Result.getValue(1); 6526 } else 6527 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6528 return true; 6529 } 6530 6531 // Don't expand it if there isn't cheap fsub instruction. 6532 if (!isOperationLegalOrCustom( 6533 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 6534 return false; 6535 6536 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 6537 SDValue Sel; 6538 6539 if (Node->isStrictFPOpcode()) { 6540 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 6541 Node->getOperand(0), /*IsSignaling*/ true); 6542 Chain = Sel.getValue(1); 6543 } else { 6544 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 6545 } 6546 6547 bool Strict = Node->isStrictFPOpcode() || 6548 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 6549 6550 if (Strict) { 6551 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 6552 // signmask then offset (the result of which should be fully representable). 6553 // Sel = Src < 0x8000000000000000 6554 // FltOfs = select Sel, 0, 0x8000000000000000 6555 // IntOfs = select Sel, 0, 0x8000000000000000 6556 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 6557 6558 // TODO: Should any fast-math-flags be set for the FSUB? 6559 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 6560 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 6561 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6562 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 6563 DAG.getConstant(0, dl, DstVT), 6564 DAG.getConstant(SignMask, dl, DstVT)); 6565 SDValue SInt; 6566 if (Node->isStrictFPOpcode()) { 6567 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 6568 { Chain, Src, FltOfs }); 6569 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6570 { Val.getValue(1), Val }); 6571 Chain = SInt.getValue(1); 6572 } else { 6573 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 6574 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 6575 } 6576 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 6577 } else { 6578 // Expand based on maximum range of FP_TO_SINT: 6579 // True = fp_to_sint(Src) 6580 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 6581 // Result = select (Src < 0x8000000000000000), True, False 6582 6583 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6584 // TODO: Should any fast-math-flags be set for the FSUB? 6585 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 6586 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 6587 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 6588 DAG.getConstant(SignMask, dl, DstVT)); 6589 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6590 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 6591 } 6592 return true; 6593 } 6594 6595 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 6596 SDValue &Chain, 6597 SelectionDAG &DAG) const { 6598 // This transform is not correct for converting 0 when rounding mode is set 6599 // to round toward negative infinity which will produce -0.0. So disable under 6600 // strictfp. 6601 if (Node->isStrictFPOpcode()) 6602 return false; 6603 6604 SDValue Src = Node->getOperand(0); 6605 EVT SrcVT = Src.getValueType(); 6606 EVT DstVT = Node->getValueType(0); 6607 6608 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 6609 return false; 6610 6611 // Only expand vector types if we have the appropriate vector bit operations. 6612 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 6613 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 6614 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 6615 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 6616 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 6617 return false; 6618 6619 SDLoc dl(SDValue(Node, 0)); 6620 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 6621 6622 // Implementation of unsigned i64 to f64 following the algorithm in 6623 // __floatundidf in compiler_rt. This implementation performs rounding 6624 // correctly in all rounding modes with the exception of converting 0 6625 // when rounding toward negative infinity. In that case the fsub will produce 6626 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 6627 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 6628 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 6629 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 6630 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 6631 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 6632 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 6633 6634 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 6635 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 6636 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 6637 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 6638 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 6639 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 6640 SDValue HiSub = 6641 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 6642 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 6643 return true; 6644 } 6645 6646 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 6647 SelectionDAG &DAG) const { 6648 SDLoc dl(Node); 6649 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 6650 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 6651 EVT VT = Node->getValueType(0); 6652 6653 if (VT.isScalableVector()) 6654 report_fatal_error( 6655 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 6656 6657 if (isOperationLegalOrCustom(NewOp, VT)) { 6658 SDValue Quiet0 = Node->getOperand(0); 6659 SDValue Quiet1 = Node->getOperand(1); 6660 6661 if (!Node->getFlags().hasNoNaNs()) { 6662 // Insert canonicalizes if it's possible we need to quiet to get correct 6663 // sNaN behavior. 6664 if (!DAG.isKnownNeverSNaN(Quiet0)) { 6665 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 6666 Node->getFlags()); 6667 } 6668 if (!DAG.isKnownNeverSNaN(Quiet1)) { 6669 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 6670 Node->getFlags()); 6671 } 6672 } 6673 6674 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 6675 } 6676 6677 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 6678 // instead if there are no NaNs. 6679 if (Node->getFlags().hasNoNaNs()) { 6680 unsigned IEEE2018Op = 6681 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 6682 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 6683 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 6684 Node->getOperand(1), Node->getFlags()); 6685 } 6686 } 6687 6688 // If none of the above worked, but there are no NaNs, then expand to 6689 // a compare/select sequence. This is required for correctness since 6690 // InstCombine might have canonicalized a fcmp+select sequence to a 6691 // FMINNUM/FMAXNUM node. If we were to fall through to the default 6692 // expansion to libcall, we might introduce a link-time dependency 6693 // on libm into a file that originally did not have one. 6694 if (Node->getFlags().hasNoNaNs()) { 6695 ISD::CondCode Pred = 6696 Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 6697 SDValue Op1 = Node->getOperand(0); 6698 SDValue Op2 = Node->getOperand(1); 6699 SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred); 6700 // Copy FMF flags, but always set the no-signed-zeros flag 6701 // as this is implied by the FMINNUM/FMAXNUM semantics. 6702 SDNodeFlags Flags = Node->getFlags(); 6703 Flags.setNoSignedZeros(true); 6704 SelCC->setFlags(Flags); 6705 return SelCC; 6706 } 6707 6708 return SDValue(); 6709 } 6710 6711 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 6712 SelectionDAG &DAG) const { 6713 SDLoc dl(Node); 6714 EVT VT = Node->getValueType(0); 6715 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6716 SDValue Op = Node->getOperand(0); 6717 unsigned Len = VT.getScalarSizeInBits(); 6718 assert(VT.isInteger() && "CTPOP not implemented for this type."); 6719 6720 // TODO: Add support for irregular type lengths. 6721 if (!(Len <= 128 && Len % 8 == 0)) 6722 return false; 6723 6724 // Only expand vector types if we have the appropriate vector bit operations. 6725 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 6726 !isOperationLegalOrCustom(ISD::SUB, VT) || 6727 !isOperationLegalOrCustom(ISD::SRL, VT) || 6728 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 6729 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6730 return false; 6731 6732 // This is the "best" algorithm from 6733 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 6734 SDValue Mask55 = 6735 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 6736 SDValue Mask33 = 6737 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 6738 SDValue Mask0F = 6739 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 6740 SDValue Mask01 = 6741 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 6742 6743 // v = v - ((v >> 1) & 0x55555555...) 6744 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 6745 DAG.getNode(ISD::AND, dl, VT, 6746 DAG.getNode(ISD::SRL, dl, VT, Op, 6747 DAG.getConstant(1, dl, ShVT)), 6748 Mask55)); 6749 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 6750 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 6751 DAG.getNode(ISD::AND, dl, VT, 6752 DAG.getNode(ISD::SRL, dl, VT, Op, 6753 DAG.getConstant(2, dl, ShVT)), 6754 Mask33)); 6755 // v = (v + (v >> 4)) & 0x0F0F0F0F... 6756 Op = DAG.getNode(ISD::AND, dl, VT, 6757 DAG.getNode(ISD::ADD, dl, VT, Op, 6758 DAG.getNode(ISD::SRL, dl, VT, Op, 6759 DAG.getConstant(4, dl, ShVT))), 6760 Mask0F); 6761 // v = (v * 0x01010101...) >> (Len - 8) 6762 if (Len > 8) 6763 Op = 6764 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 6765 DAG.getConstant(Len - 8, dl, ShVT)); 6766 6767 Result = Op; 6768 return true; 6769 } 6770 6771 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 6772 SelectionDAG &DAG) const { 6773 SDLoc dl(Node); 6774 EVT VT = Node->getValueType(0); 6775 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6776 SDValue Op = Node->getOperand(0); 6777 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6778 6779 // If the non-ZERO_UNDEF version is supported we can use that instead. 6780 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 6781 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 6782 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 6783 return true; 6784 } 6785 6786 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6787 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 6788 EVT SetCCVT = 6789 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6790 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 6791 SDValue Zero = DAG.getConstant(0, dl, VT); 6792 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6793 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6794 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 6795 return true; 6796 } 6797 6798 // Only expand vector types if we have the appropriate vector bit operations. 6799 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6800 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 6801 !isOperationLegalOrCustom(ISD::SRL, VT) || 6802 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6803 return false; 6804 6805 // for now, we do this: 6806 // x = x | (x >> 1); 6807 // x = x | (x >> 2); 6808 // ... 6809 // x = x | (x >>16); 6810 // x = x | (x >>32); // for 64-bit input 6811 // return popcount(~x); 6812 // 6813 // Ref: "Hacker's Delight" by Henry Warren 6814 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 6815 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 6816 Op = DAG.getNode(ISD::OR, dl, VT, Op, 6817 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 6818 } 6819 Op = DAG.getNOT(dl, Op, VT); 6820 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 6821 return true; 6822 } 6823 6824 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 6825 SelectionDAG &DAG) const { 6826 SDLoc dl(Node); 6827 EVT VT = Node->getValueType(0); 6828 SDValue Op = Node->getOperand(0); 6829 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6830 6831 // If the non-ZERO_UNDEF version is supported we can use that instead. 6832 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 6833 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 6834 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 6835 return true; 6836 } 6837 6838 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6839 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 6840 EVT SetCCVT = 6841 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6842 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 6843 SDValue Zero = DAG.getConstant(0, dl, VT); 6844 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6845 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6846 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 6847 return true; 6848 } 6849 6850 // Only expand vector types if we have the appropriate vector bit operations. 6851 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6852 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 6853 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 6854 !isOperationLegalOrCustom(ISD::SUB, VT) || 6855 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 6856 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 6857 return false; 6858 6859 // for now, we use: { return popcount(~x & (x - 1)); } 6860 // unless the target has ctlz but not ctpop, in which case we use: 6861 // { return 32 - nlz(~x & (x-1)); } 6862 // Ref: "Hacker's Delight" by Henry Warren 6863 SDValue Tmp = DAG.getNode( 6864 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 6865 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 6866 6867 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 6868 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 6869 Result = 6870 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 6871 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 6872 return true; 6873 } 6874 6875 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 6876 return true; 6877 } 6878 6879 bool TargetLowering::expandABS(SDNode *N, SDValue &Result, 6880 SelectionDAG &DAG, bool IsNegative) const { 6881 SDLoc dl(N); 6882 EVT VT = N->getValueType(0); 6883 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6884 SDValue Op = N->getOperand(0); 6885 6886 // abs(x) -> smax(x,sub(0,x)) 6887 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 6888 isOperationLegal(ISD::SMAX, VT)) { 6889 SDValue Zero = DAG.getConstant(0, dl, VT); 6890 Result = DAG.getNode(ISD::SMAX, dl, VT, Op, 6891 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6892 return true; 6893 } 6894 6895 // abs(x) -> umin(x,sub(0,x)) 6896 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 6897 isOperationLegal(ISD::UMIN, VT)) { 6898 SDValue Zero = DAG.getConstant(0, dl, VT); 6899 Result = DAG.getNode(ISD::UMIN, dl, VT, Op, 6900 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6901 return true; 6902 } 6903 6904 // 0 - abs(x) -> smin(x, sub(0,x)) 6905 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 6906 isOperationLegal(ISD::SMIN, VT)) { 6907 SDValue Zero = DAG.getConstant(0, dl, VT); 6908 Result = DAG.getNode(ISD::SMIN, dl, VT, Op, 6909 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6910 return true; 6911 } 6912 6913 // Only expand vector types if we have the appropriate vector operations. 6914 if (VT.isVector() && 6915 (!isOperationLegalOrCustom(ISD::SRA, VT) || 6916 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 6917 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 6918 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 6919 return false; 6920 6921 SDValue Shift = 6922 DAG.getNode(ISD::SRA, dl, VT, Op, 6923 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 6924 if (!IsNegative) { 6925 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift); 6926 Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift); 6927 } else { 6928 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 6929 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 6930 Result = DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 6931 } 6932 return true; 6933 } 6934 6935 std::pair<SDValue, SDValue> 6936 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 6937 SelectionDAG &DAG) const { 6938 SDLoc SL(LD); 6939 SDValue Chain = LD->getChain(); 6940 SDValue BasePTR = LD->getBasePtr(); 6941 EVT SrcVT = LD->getMemoryVT(); 6942 EVT DstVT = LD->getValueType(0); 6943 ISD::LoadExtType ExtType = LD->getExtensionType(); 6944 6945 if (SrcVT.isScalableVector()) 6946 report_fatal_error("Cannot scalarize scalable vector loads"); 6947 6948 unsigned NumElem = SrcVT.getVectorNumElements(); 6949 6950 EVT SrcEltVT = SrcVT.getScalarType(); 6951 EVT DstEltVT = DstVT.getScalarType(); 6952 6953 // A vector must always be stored in memory as-is, i.e. without any padding 6954 // between the elements, since various code depend on it, e.g. in the 6955 // handling of a bitcast of a vector type to int, which may be done with a 6956 // vector store followed by an integer load. A vector that does not have 6957 // elements that are byte-sized must therefore be stored as an integer 6958 // built out of the extracted vector elements. 6959 if (!SrcEltVT.isByteSized()) { 6960 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 6961 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 6962 6963 unsigned NumSrcBits = SrcVT.getSizeInBits(); 6964 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 6965 6966 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 6967 SDValue SrcEltBitMask = DAG.getConstant( 6968 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 6969 6970 // Load the whole vector and avoid masking off the top bits as it makes 6971 // the codegen worse. 6972 SDValue Load = 6973 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 6974 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 6975 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 6976 6977 SmallVector<SDValue, 8> Vals; 6978 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 6979 unsigned ShiftIntoIdx = 6980 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 6981 SDValue ShiftAmount = 6982 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 6983 LoadVT, SL, /*LegalTypes=*/false); 6984 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 6985 SDValue Elt = 6986 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 6987 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 6988 6989 if (ExtType != ISD::NON_EXTLOAD) { 6990 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 6991 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 6992 } 6993 6994 Vals.push_back(Scalar); 6995 } 6996 6997 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 6998 return std::make_pair(Value, Load.getValue(1)); 6999 } 7000 7001 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 7002 assert(SrcEltVT.isByteSized()); 7003 7004 SmallVector<SDValue, 8> Vals; 7005 SmallVector<SDValue, 8> LoadChains; 7006 7007 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7008 SDValue ScalarLoad = 7009 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 7010 LD->getPointerInfo().getWithOffset(Idx * Stride), 7011 SrcEltVT, LD->getOriginalAlign(), 7012 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7013 7014 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 7015 7016 Vals.push_back(ScalarLoad.getValue(0)); 7017 LoadChains.push_back(ScalarLoad.getValue(1)); 7018 } 7019 7020 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 7021 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7022 7023 return std::make_pair(Value, NewChain); 7024 } 7025 7026 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 7027 SelectionDAG &DAG) const { 7028 SDLoc SL(ST); 7029 7030 SDValue Chain = ST->getChain(); 7031 SDValue BasePtr = ST->getBasePtr(); 7032 SDValue Value = ST->getValue(); 7033 EVT StVT = ST->getMemoryVT(); 7034 7035 if (StVT.isScalableVector()) 7036 report_fatal_error("Cannot scalarize scalable vector stores"); 7037 7038 // The type of the data we want to save 7039 EVT RegVT = Value.getValueType(); 7040 EVT RegSclVT = RegVT.getScalarType(); 7041 7042 // The type of data as saved in memory. 7043 EVT MemSclVT = StVT.getScalarType(); 7044 7045 unsigned NumElem = StVT.getVectorNumElements(); 7046 7047 // A vector must always be stored in memory as-is, i.e. without any padding 7048 // between the elements, since various code depend on it, e.g. in the 7049 // handling of a bitcast of a vector type to int, which may be done with a 7050 // vector store followed by an integer load. A vector that does not have 7051 // elements that are byte-sized must therefore be stored as an integer 7052 // built out of the extracted vector elements. 7053 if (!MemSclVT.isByteSized()) { 7054 unsigned NumBits = StVT.getSizeInBits(); 7055 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 7056 7057 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 7058 7059 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7060 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7061 DAG.getVectorIdxConstant(Idx, SL)); 7062 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 7063 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 7064 unsigned ShiftIntoIdx = 7065 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7066 SDValue ShiftAmount = 7067 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 7068 SDValue ShiftedElt = 7069 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 7070 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 7071 } 7072 7073 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 7074 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7075 ST->getAAInfo()); 7076 } 7077 7078 // Store Stride in bytes 7079 unsigned Stride = MemSclVT.getSizeInBits() / 8; 7080 assert(Stride && "Zero stride!"); 7081 // Extract each of the elements from the original vector and save them into 7082 // memory individually. 7083 SmallVector<SDValue, 8> Stores; 7084 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7085 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7086 DAG.getVectorIdxConstant(Idx, SL)); 7087 7088 SDValue Ptr = 7089 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 7090 7091 // This scalar TruncStore may be illegal, but we legalize it later. 7092 SDValue Store = DAG.getTruncStore( 7093 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 7094 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7095 ST->getAAInfo()); 7096 7097 Stores.push_back(Store); 7098 } 7099 7100 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 7101 } 7102 7103 std::pair<SDValue, SDValue> 7104 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 7105 assert(LD->getAddressingMode() == ISD::UNINDEXED && 7106 "unaligned indexed loads not implemented!"); 7107 SDValue Chain = LD->getChain(); 7108 SDValue Ptr = LD->getBasePtr(); 7109 EVT VT = LD->getValueType(0); 7110 EVT LoadedVT = LD->getMemoryVT(); 7111 SDLoc dl(LD); 7112 auto &MF = DAG.getMachineFunction(); 7113 7114 if (VT.isFloatingPoint() || VT.isVector()) { 7115 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 7116 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 7117 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 7118 LoadedVT.isVector()) { 7119 // Scalarize the load and let the individual components be handled. 7120 return scalarizeVectorLoad(LD, DAG); 7121 } 7122 7123 // Expand to a (misaligned) integer load of the same size, 7124 // then bitconvert to floating point or vector. 7125 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 7126 LD->getMemOperand()); 7127 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 7128 if (LoadedVT != VT) 7129 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 7130 ISD::ANY_EXTEND, dl, VT, Result); 7131 7132 return std::make_pair(Result, newLoad.getValue(1)); 7133 } 7134 7135 // Copy the value to a (aligned) stack slot using (unaligned) integer 7136 // loads and stores, then do a (aligned) load from the stack slot. 7137 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 7138 unsigned LoadedBytes = LoadedVT.getStoreSize(); 7139 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7140 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 7141 7142 // Make sure the stack slot is also aligned for the register type. 7143 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 7144 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 7145 SmallVector<SDValue, 8> Stores; 7146 SDValue StackPtr = StackBase; 7147 unsigned Offset = 0; 7148 7149 EVT PtrVT = Ptr.getValueType(); 7150 EVT StackPtrVT = StackPtr.getValueType(); 7151 7152 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7153 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7154 7155 // Do all but one copies using the full register width. 7156 for (unsigned i = 1; i < NumRegs; i++) { 7157 // Load one integer register's worth from the original location. 7158 SDValue Load = DAG.getLoad( 7159 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 7160 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7161 LD->getAAInfo()); 7162 // Follow the load with a store to the stack slot. Remember the store. 7163 Stores.push_back(DAG.getStore( 7164 Load.getValue(1), dl, Load, StackPtr, 7165 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 7166 // Increment the pointers. 7167 Offset += RegBytes; 7168 7169 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7170 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7171 } 7172 7173 // The last copy may be partial. Do an extending load. 7174 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 7175 8 * (LoadedBytes - Offset)); 7176 SDValue Load = 7177 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 7178 LD->getPointerInfo().getWithOffset(Offset), MemVT, 7179 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7180 LD->getAAInfo()); 7181 // Follow the load with a store to the stack slot. Remember the store. 7182 // On big-endian machines this requires a truncating store to ensure 7183 // that the bits end up in the right place. 7184 Stores.push_back(DAG.getTruncStore( 7185 Load.getValue(1), dl, Load, StackPtr, 7186 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 7187 7188 // The order of the stores doesn't matter - say it with a TokenFactor. 7189 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7190 7191 // Finally, perform the original load only redirected to the stack slot. 7192 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 7193 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 7194 LoadedVT); 7195 7196 // Callers expect a MERGE_VALUES node. 7197 return std::make_pair(Load, TF); 7198 } 7199 7200 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 7201 "Unaligned load of unsupported type."); 7202 7203 // Compute the new VT that is half the size of the old one. This is an 7204 // integer MVT. 7205 unsigned NumBits = LoadedVT.getSizeInBits(); 7206 EVT NewLoadedVT; 7207 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 7208 NumBits >>= 1; 7209 7210 Align Alignment = LD->getOriginalAlign(); 7211 unsigned IncrementSize = NumBits / 8; 7212 ISD::LoadExtType HiExtType = LD->getExtensionType(); 7213 7214 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 7215 if (HiExtType == ISD::NON_EXTLOAD) 7216 HiExtType = ISD::ZEXTLOAD; 7217 7218 // Load the value in two parts 7219 SDValue Lo, Hi; 7220 if (DAG.getDataLayout().isLittleEndian()) { 7221 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7222 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7223 LD->getAAInfo()); 7224 7225 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7226 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 7227 LD->getPointerInfo().getWithOffset(IncrementSize), 7228 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7229 LD->getAAInfo()); 7230 } else { 7231 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7232 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7233 LD->getAAInfo()); 7234 7235 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7236 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 7237 LD->getPointerInfo().getWithOffset(IncrementSize), 7238 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7239 LD->getAAInfo()); 7240 } 7241 7242 // aggregate the two parts 7243 SDValue ShiftAmount = 7244 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 7245 DAG.getDataLayout())); 7246 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 7247 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 7248 7249 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 7250 Hi.getValue(1)); 7251 7252 return std::make_pair(Result, TF); 7253 } 7254 7255 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 7256 SelectionDAG &DAG) const { 7257 assert(ST->getAddressingMode() == ISD::UNINDEXED && 7258 "unaligned indexed stores not implemented!"); 7259 SDValue Chain = ST->getChain(); 7260 SDValue Ptr = ST->getBasePtr(); 7261 SDValue Val = ST->getValue(); 7262 EVT VT = Val.getValueType(); 7263 Align Alignment = ST->getOriginalAlign(); 7264 auto &MF = DAG.getMachineFunction(); 7265 EVT StoreMemVT = ST->getMemoryVT(); 7266 7267 SDLoc dl(ST); 7268 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 7269 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7270 if (isTypeLegal(intVT)) { 7271 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 7272 StoreMemVT.isVector()) { 7273 // Scalarize the store and let the individual components be handled. 7274 SDValue Result = scalarizeVectorStore(ST, DAG); 7275 return Result; 7276 } 7277 // Expand to a bitconvert of the value to the integer type of the 7278 // same size, then a (misaligned) int store. 7279 // FIXME: Does not handle truncating floating point stores! 7280 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 7281 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 7282 Alignment, ST->getMemOperand()->getFlags()); 7283 return Result; 7284 } 7285 // Do a (aligned) store to a stack slot, then copy from the stack slot 7286 // to the final destination using (unaligned) integer loads and stores. 7287 MVT RegVT = getRegisterType( 7288 *DAG.getContext(), 7289 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 7290 EVT PtrVT = Ptr.getValueType(); 7291 unsigned StoredBytes = StoreMemVT.getStoreSize(); 7292 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7293 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 7294 7295 // Make sure the stack slot is also aligned for the register type. 7296 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 7297 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 7298 7299 // Perform the original store, only redirected to the stack slot. 7300 SDValue Store = DAG.getTruncStore( 7301 Chain, dl, Val, StackPtr, 7302 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 7303 7304 EVT StackPtrVT = StackPtr.getValueType(); 7305 7306 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7307 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7308 SmallVector<SDValue, 8> Stores; 7309 unsigned Offset = 0; 7310 7311 // Do all but one copies using the full register width. 7312 for (unsigned i = 1; i < NumRegs; i++) { 7313 // Load one integer register's worth from the stack slot. 7314 SDValue Load = DAG.getLoad( 7315 RegVT, dl, Store, StackPtr, 7316 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 7317 // Store it to the final location. Remember the store. 7318 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 7319 ST->getPointerInfo().getWithOffset(Offset), 7320 ST->getOriginalAlign(), 7321 ST->getMemOperand()->getFlags())); 7322 // Increment the pointers. 7323 Offset += RegBytes; 7324 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7325 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7326 } 7327 7328 // The last store may be partial. Do a truncating store. On big-endian 7329 // machines this requires an extending load from the stack slot to ensure 7330 // that the bits are in the right place. 7331 EVT LoadMemVT = 7332 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 7333 7334 // Load from the stack slot. 7335 SDValue Load = DAG.getExtLoad( 7336 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 7337 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 7338 7339 Stores.push_back( 7340 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 7341 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 7342 ST->getOriginalAlign(), 7343 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 7344 // The order of the stores doesn't matter - say it with a TokenFactor. 7345 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7346 return Result; 7347 } 7348 7349 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 7350 "Unaligned store of unknown type."); 7351 // Get the half-size VT 7352 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 7353 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 7354 unsigned IncrementSize = NumBits / 8; 7355 7356 // Divide the stored value in two parts. 7357 SDValue ShiftAmount = DAG.getConstant( 7358 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 7359 SDValue Lo = Val; 7360 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 7361 7362 // Store the two parts 7363 SDValue Store1, Store2; 7364 Store1 = DAG.getTruncStore(Chain, dl, 7365 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 7366 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 7367 ST->getMemOperand()->getFlags()); 7368 7369 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7370 Store2 = DAG.getTruncStore( 7371 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 7372 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 7373 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 7374 7375 SDValue Result = 7376 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 7377 return Result; 7378 } 7379 7380 SDValue 7381 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 7382 const SDLoc &DL, EVT DataVT, 7383 SelectionDAG &DAG, 7384 bool IsCompressedMemory) const { 7385 SDValue Increment; 7386 EVT AddrVT = Addr.getValueType(); 7387 EVT MaskVT = Mask.getValueType(); 7388 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 7389 "Incompatible types of Data and Mask"); 7390 if (IsCompressedMemory) { 7391 if (DataVT.isScalableVector()) 7392 report_fatal_error( 7393 "Cannot currently handle compressed memory with scalable vectors"); 7394 // Incrementing the pointer according to number of '1's in the mask. 7395 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 7396 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 7397 if (MaskIntVT.getSizeInBits() < 32) { 7398 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 7399 MaskIntVT = MVT::i32; 7400 } 7401 7402 // Count '1's with POPCNT. 7403 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 7404 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 7405 // Scale is an element size in bytes. 7406 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 7407 AddrVT); 7408 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 7409 } else if (DataVT.isScalableVector()) { 7410 Increment = DAG.getVScale(DL, AddrVT, 7411 APInt(AddrVT.getFixedSizeInBits(), 7412 DataVT.getStoreSize().getKnownMinSize())); 7413 } else 7414 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 7415 7416 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 7417 } 7418 7419 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 7420 SDValue Idx, 7421 EVT VecVT, 7422 const SDLoc &dl) { 7423 if (!VecVT.isScalableVector() && isa<ConstantSDNode>(Idx)) 7424 return Idx; 7425 7426 EVT IdxVT = Idx.getValueType(); 7427 unsigned NElts = VecVT.getVectorMinNumElements(); 7428 if (VecVT.isScalableVector()) { 7429 SDValue VS = DAG.getVScale(dl, IdxVT, 7430 APInt(IdxVT.getFixedSizeInBits(), 7431 NElts)); 7432 SDValue Sub = DAG.getNode(ISD::SUB, dl, IdxVT, VS, 7433 DAG.getConstant(1, dl, IdxVT)); 7434 7435 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 7436 } else { 7437 if (isPowerOf2_32(NElts)) { 7438 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 7439 Log2_32(NElts)); 7440 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 7441 DAG.getConstant(Imm, dl, IdxVT)); 7442 } 7443 } 7444 7445 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 7446 DAG.getConstant(NElts - 1, dl, IdxVT)); 7447 } 7448 7449 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 7450 SDValue VecPtr, EVT VecVT, 7451 SDValue Index) const { 7452 SDLoc dl(Index); 7453 // Make sure the index type is big enough to compute in. 7454 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 7455 7456 EVT EltVT = VecVT.getVectorElementType(); 7457 7458 // Calculate the element offset and add it to the pointer. 7459 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 7460 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 7461 "Converting bits to bytes lost precision"); 7462 7463 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 7464 7465 EVT IdxVT = Index.getValueType(); 7466 7467 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 7468 DAG.getConstant(EltSize, dl, IdxVT)); 7469 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 7470 } 7471 7472 //===----------------------------------------------------------------------===// 7473 // Implementation of Emulated TLS Model 7474 //===----------------------------------------------------------------------===// 7475 7476 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 7477 SelectionDAG &DAG) const { 7478 // Access to address of TLS varialbe xyz is lowered to a function call: 7479 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 7480 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7481 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 7482 SDLoc dl(GA); 7483 7484 ArgListTy Args; 7485 ArgListEntry Entry; 7486 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 7487 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 7488 StringRef EmuTlsVarName(NameString); 7489 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 7490 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 7491 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 7492 Entry.Ty = VoidPtrType; 7493 Args.push_back(Entry); 7494 7495 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 7496 7497 TargetLowering::CallLoweringInfo CLI(DAG); 7498 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 7499 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 7500 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7501 7502 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7503 // At last for X86 targets, maybe good for other targets too? 7504 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7505 MFI.setAdjustsStack(true); // Is this only for X86 target? 7506 MFI.setHasCalls(true); 7507 7508 assert((GA->getOffset() == 0) && 7509 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 7510 return CallResult.first; 7511 } 7512 7513 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 7514 SelectionDAG &DAG) const { 7515 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 7516 if (!isCtlzFast()) 7517 return SDValue(); 7518 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7519 SDLoc dl(Op); 7520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7521 if (C->isNullValue() && CC == ISD::SETEQ) { 7522 EVT VT = Op.getOperand(0).getValueType(); 7523 SDValue Zext = Op.getOperand(0); 7524 if (VT.bitsLT(MVT::i32)) { 7525 VT = MVT::i32; 7526 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 7527 } 7528 unsigned Log2b = Log2_32(VT.getSizeInBits()); 7529 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 7530 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 7531 DAG.getConstant(Log2b, dl, MVT::i32)); 7532 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 7533 } 7534 } 7535 return SDValue(); 7536 } 7537 7538 // Convert redundant addressing modes (e.g. scaling is redundant 7539 // when accessing bytes). 7540 ISD::MemIndexType 7541 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT, 7542 SDValue Offsets) const { 7543 bool IsScaledIndex = 7544 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED); 7545 bool IsSignedIndex = 7546 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED); 7547 7548 // Scaling is unimportant for bytes, canonicalize to unscaled. 7549 if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) { 7550 IsScaledIndex = false; 7551 IndexType = IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED; 7552 } 7553 7554 return IndexType; 7555 } 7556 7557 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 7558 SDValue Op0 = Node->getOperand(0); 7559 SDValue Op1 = Node->getOperand(1); 7560 EVT VT = Op0.getValueType(); 7561 unsigned Opcode = Node->getOpcode(); 7562 SDLoc DL(Node); 7563 7564 // umin(x,y) -> sub(x,usubsat(x,y)) 7565 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 7566 isOperationLegal(ISD::USUBSAT, VT)) { 7567 return DAG.getNode(ISD::SUB, DL, VT, Op0, 7568 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 7569 } 7570 7571 // umax(x,y) -> add(x,usubsat(y,x)) 7572 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 7573 isOperationLegal(ISD::USUBSAT, VT)) { 7574 return DAG.getNode(ISD::ADD, DL, VT, Op0, 7575 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 7576 } 7577 7578 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 7579 ISD::CondCode CC; 7580 switch (Opcode) { 7581 default: llvm_unreachable("How did we get here?"); 7582 case ISD::SMAX: CC = ISD::SETGT; break; 7583 case ISD::SMIN: CC = ISD::SETLT; break; 7584 case ISD::UMAX: CC = ISD::SETUGT; break; 7585 case ISD::UMIN: CC = ISD::SETULT; break; 7586 } 7587 7588 // FIXME: Should really try to split the vector in case it's legal on a 7589 // subvector. 7590 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7591 return DAG.UnrollVectorOp(Node); 7592 7593 SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC); 7594 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 7595 } 7596 7597 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 7598 unsigned Opcode = Node->getOpcode(); 7599 SDValue LHS = Node->getOperand(0); 7600 SDValue RHS = Node->getOperand(1); 7601 EVT VT = LHS.getValueType(); 7602 SDLoc dl(Node); 7603 7604 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7605 assert(VT.isInteger() && "Expected operands to be integers"); 7606 7607 // usub.sat(a, b) -> umax(a, b) - b 7608 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 7609 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 7610 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 7611 } 7612 7613 // uadd.sat(a, b) -> umin(a, ~b) + b 7614 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 7615 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 7616 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 7617 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 7618 } 7619 7620 unsigned OverflowOp; 7621 switch (Opcode) { 7622 case ISD::SADDSAT: 7623 OverflowOp = ISD::SADDO; 7624 break; 7625 case ISD::UADDSAT: 7626 OverflowOp = ISD::UADDO; 7627 break; 7628 case ISD::SSUBSAT: 7629 OverflowOp = ISD::SSUBO; 7630 break; 7631 case ISD::USUBSAT: 7632 OverflowOp = ISD::USUBO; 7633 break; 7634 default: 7635 llvm_unreachable("Expected method to receive signed or unsigned saturation " 7636 "addition or subtraction node."); 7637 } 7638 7639 // FIXME: Should really try to split the vector in case it's legal on a 7640 // subvector. 7641 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7642 return DAG.UnrollVectorOp(Node); 7643 7644 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 7645 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7646 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), 7647 LHS, RHS); 7648 SDValue SumDiff = Result.getValue(0); 7649 SDValue Overflow = Result.getValue(1); 7650 SDValue Zero = DAG.getConstant(0, dl, VT); 7651 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 7652 7653 if (Opcode == ISD::UADDSAT) { 7654 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7655 // (LHS + RHS) | OverflowMask 7656 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7657 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 7658 } 7659 // Overflow ? 0xffff.... : (LHS + RHS) 7660 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 7661 } else if (Opcode == ISD::USUBSAT) { 7662 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7663 // (LHS - RHS) & ~OverflowMask 7664 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7665 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 7666 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 7667 } 7668 // Overflow ? 0 : (LHS - RHS) 7669 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 7670 } else { 7671 // SatMax -> Overflow && SumDiff < 0 7672 // SatMin -> Overflow && SumDiff >= 0 7673 APInt MinVal = APInt::getSignedMinValue(BitWidth); 7674 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 7675 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7676 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7677 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 7678 Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin); 7679 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 7680 } 7681 } 7682 7683 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 7684 unsigned Opcode = Node->getOpcode(); 7685 bool IsSigned = Opcode == ISD::SSHLSAT; 7686 SDValue LHS = Node->getOperand(0); 7687 SDValue RHS = Node->getOperand(1); 7688 EVT VT = LHS.getValueType(); 7689 SDLoc dl(Node); 7690 7691 assert((Node->getOpcode() == ISD::SSHLSAT || 7692 Node->getOpcode() == ISD::USHLSAT) && 7693 "Expected a SHLSAT opcode"); 7694 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7695 assert(VT.isInteger() && "Expected operands to be integers"); 7696 7697 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 7698 7699 unsigned BW = VT.getScalarSizeInBits(); 7700 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 7701 SDValue Orig = 7702 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 7703 7704 SDValue SatVal; 7705 if (IsSigned) { 7706 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 7707 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 7708 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 7709 SatMin, SatMax, ISD::SETLT); 7710 } else { 7711 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 7712 } 7713 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 7714 7715 return Result; 7716 } 7717 7718 SDValue 7719 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 7720 assert((Node->getOpcode() == ISD::SMULFIX || 7721 Node->getOpcode() == ISD::UMULFIX || 7722 Node->getOpcode() == ISD::SMULFIXSAT || 7723 Node->getOpcode() == ISD::UMULFIXSAT) && 7724 "Expected a fixed point multiplication opcode"); 7725 7726 SDLoc dl(Node); 7727 SDValue LHS = Node->getOperand(0); 7728 SDValue RHS = Node->getOperand(1); 7729 EVT VT = LHS.getValueType(); 7730 unsigned Scale = Node->getConstantOperandVal(2); 7731 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 7732 Node->getOpcode() == ISD::UMULFIXSAT); 7733 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 7734 Node->getOpcode() == ISD::SMULFIXSAT); 7735 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7736 unsigned VTSize = VT.getScalarSizeInBits(); 7737 7738 if (!Scale) { 7739 // [us]mul.fix(a, b, 0) -> mul(a, b) 7740 if (!Saturating) { 7741 if (isOperationLegalOrCustom(ISD::MUL, VT)) 7742 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 7743 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 7744 SDValue Result = 7745 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7746 SDValue Product = Result.getValue(0); 7747 SDValue Overflow = Result.getValue(1); 7748 SDValue Zero = DAG.getConstant(0, dl, VT); 7749 7750 APInt MinVal = APInt::getSignedMinValue(VTSize); 7751 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 7752 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7753 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7754 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT); 7755 Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin); 7756 return DAG.getSelect(dl, VT, Overflow, Result, Product); 7757 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 7758 SDValue Result = 7759 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7760 SDValue Product = Result.getValue(0); 7761 SDValue Overflow = Result.getValue(1); 7762 7763 APInt MaxVal = APInt::getMaxValue(VTSize); 7764 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7765 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 7766 } 7767 } 7768 7769 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 7770 "Expected scale to be less than the number of bits if signed or at " 7771 "most the number of bits if unsigned."); 7772 assert(LHS.getValueType() == RHS.getValueType() && 7773 "Expected both operands to be the same type"); 7774 7775 // Get the upper and lower bits of the result. 7776 SDValue Lo, Hi; 7777 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 7778 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 7779 if (isOperationLegalOrCustom(LoHiOp, VT)) { 7780 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 7781 Lo = Result.getValue(0); 7782 Hi = Result.getValue(1); 7783 } else if (isOperationLegalOrCustom(HiOp, VT)) { 7784 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 7785 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 7786 } else if (VT.isVector()) { 7787 return SDValue(); 7788 } else { 7789 report_fatal_error("Unable to expand fixed point multiplication."); 7790 } 7791 7792 if (Scale == VTSize) 7793 // Result is just the top half since we'd be shifting by the width of the 7794 // operand. Overflow impossible so this works for both UMULFIX and 7795 // UMULFIXSAT. 7796 return Hi; 7797 7798 // The result will need to be shifted right by the scale since both operands 7799 // are scaled. The result is given to us in 2 halves, so we only want part of 7800 // both in the result. 7801 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 7802 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 7803 DAG.getConstant(Scale, dl, ShiftTy)); 7804 if (!Saturating) 7805 return Result; 7806 7807 if (!Signed) { 7808 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 7809 // widened multiplication) aren't all zeroes. 7810 7811 // Saturate to max if ((Hi >> Scale) != 0), 7812 // which is the same as if (Hi > ((1 << Scale) - 1)) 7813 APInt MaxVal = APInt::getMaxValue(VTSize); 7814 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 7815 dl, VT); 7816 Result = DAG.getSelectCC(dl, Hi, LowMask, 7817 DAG.getConstant(MaxVal, dl, VT), Result, 7818 ISD::SETUGT); 7819 7820 return Result; 7821 } 7822 7823 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 7824 // widened multiplication) aren't all ones or all zeroes. 7825 7826 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 7827 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 7828 7829 if (Scale == 0) { 7830 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 7831 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 7832 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 7833 // Saturated to SatMin if wide product is negative, and SatMax if wide 7834 // product is positive ... 7835 SDValue Zero = DAG.getConstant(0, dl, VT); 7836 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 7837 ISD::SETLT); 7838 // ... but only if we overflowed. 7839 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 7840 } 7841 7842 // We handled Scale==0 above so all the bits to examine is in Hi. 7843 7844 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 7845 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 7846 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 7847 dl, VT); 7848 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 7849 // Saturate to min if (Hi >> (Scale - 1)) < -1), 7850 // which is the same as if (HI < (-1 << (Scale - 1)) 7851 SDValue HighMask = 7852 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 7853 dl, VT); 7854 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 7855 return Result; 7856 } 7857 7858 SDValue 7859 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 7860 SDValue LHS, SDValue RHS, 7861 unsigned Scale, SelectionDAG &DAG) const { 7862 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 7863 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 7864 "Expected a fixed point division opcode"); 7865 7866 EVT VT = LHS.getValueType(); 7867 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 7868 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 7869 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7870 7871 // If there is enough room in the type to upscale the LHS or downscale the 7872 // RHS before the division, we can perform it in this type without having to 7873 // resize. For signed operations, the LHS headroom is the number of 7874 // redundant sign bits, and for unsigned ones it is the number of zeroes. 7875 // The headroom for the RHS is the number of trailing zeroes. 7876 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 7877 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 7878 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 7879 7880 // For signed saturating operations, we need to be able to detect true integer 7881 // division overflow; that is, when you have MIN / -EPS. However, this 7882 // is undefined behavior and if we emit divisions that could take such 7883 // values it may cause undesired behavior (arithmetic exceptions on x86, for 7884 // example). 7885 // Avoid this by requiring an extra bit so that we never get this case. 7886 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 7887 // signed saturating division, we need to emit a whopping 32-bit division. 7888 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 7889 return SDValue(); 7890 7891 unsigned LHSShift = std::min(LHSLead, Scale); 7892 unsigned RHSShift = Scale - LHSShift; 7893 7894 // At this point, we know that if we shift the LHS up by LHSShift and the 7895 // RHS down by RHSShift, we can emit a regular division with a final scaling 7896 // factor of Scale. 7897 7898 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 7899 if (LHSShift) 7900 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 7901 DAG.getConstant(LHSShift, dl, ShiftTy)); 7902 if (RHSShift) 7903 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 7904 DAG.getConstant(RHSShift, dl, ShiftTy)); 7905 7906 SDValue Quot; 7907 if (Signed) { 7908 // For signed operations, if the resulting quotient is negative and the 7909 // remainder is nonzero, subtract 1 from the quotient to round towards 7910 // negative infinity. 7911 SDValue Rem; 7912 // FIXME: Ideally we would always produce an SDIVREM here, but if the 7913 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 7914 // we couldn't just form a libcall, but the type legalizer doesn't do it. 7915 if (isTypeLegal(VT) && 7916 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 7917 Quot = DAG.getNode(ISD::SDIVREM, dl, 7918 DAG.getVTList(VT, VT), 7919 LHS, RHS); 7920 Rem = Quot.getValue(1); 7921 Quot = Quot.getValue(0); 7922 } else { 7923 Quot = DAG.getNode(ISD::SDIV, dl, VT, 7924 LHS, RHS); 7925 Rem = DAG.getNode(ISD::SREM, dl, VT, 7926 LHS, RHS); 7927 } 7928 SDValue Zero = DAG.getConstant(0, dl, VT); 7929 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 7930 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 7931 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 7932 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 7933 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 7934 DAG.getConstant(1, dl, VT)); 7935 Quot = DAG.getSelect(dl, VT, 7936 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 7937 Sub1, Quot); 7938 } else 7939 Quot = DAG.getNode(ISD::UDIV, dl, VT, 7940 LHS, RHS); 7941 7942 return Quot; 7943 } 7944 7945 void TargetLowering::expandUADDSUBO( 7946 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 7947 SDLoc dl(Node); 7948 SDValue LHS = Node->getOperand(0); 7949 SDValue RHS = Node->getOperand(1); 7950 bool IsAdd = Node->getOpcode() == ISD::UADDO; 7951 7952 // If ADD/SUBCARRY is legal, use that instead. 7953 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 7954 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 7955 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 7956 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 7957 { LHS, RHS, CarryIn }); 7958 Result = SDValue(NodeCarry.getNode(), 0); 7959 Overflow = SDValue(NodeCarry.getNode(), 1); 7960 return; 7961 } 7962 7963 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 7964 LHS.getValueType(), LHS, RHS); 7965 7966 EVT ResultType = Node->getValueType(1); 7967 EVT SetCCType = getSetCCResultType( 7968 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 7969 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 7970 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 7971 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 7972 } 7973 7974 void TargetLowering::expandSADDSUBO( 7975 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 7976 SDLoc dl(Node); 7977 SDValue LHS = Node->getOperand(0); 7978 SDValue RHS = Node->getOperand(1); 7979 bool IsAdd = Node->getOpcode() == ISD::SADDO; 7980 7981 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 7982 LHS.getValueType(), LHS, RHS); 7983 7984 EVT ResultType = Node->getValueType(1); 7985 EVT OType = getSetCCResultType( 7986 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 7987 7988 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 7989 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 7990 if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) { 7991 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 7992 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 7993 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 7994 return; 7995 } 7996 7997 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 7998 7999 // For an addition, the result should be less than one of the operands (LHS) 8000 // if and only if the other operand (RHS) is negative, otherwise there will 8001 // be overflow. 8002 // For a subtraction, the result should be less than one of the operands 8003 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 8004 // otherwise there will be overflow. 8005 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 8006 SDValue ConditionRHS = 8007 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 8008 8009 Overflow = DAG.getBoolExtOrTrunc( 8010 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 8011 ResultType, ResultType); 8012 } 8013 8014 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 8015 SDValue &Overflow, SelectionDAG &DAG) const { 8016 SDLoc dl(Node); 8017 EVT VT = Node->getValueType(0); 8018 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8019 SDValue LHS = Node->getOperand(0); 8020 SDValue RHS = Node->getOperand(1); 8021 bool isSigned = Node->getOpcode() == ISD::SMULO; 8022 8023 // For power-of-two multiplications we can use a simpler shift expansion. 8024 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 8025 const APInt &C = RHSC->getAPIntValue(); 8026 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 8027 if (C.isPowerOf2()) { 8028 // smulo(x, signed_min) is same as umulo(x, signed_min). 8029 bool UseArithShift = isSigned && !C.isMinSignedValue(); 8030 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8031 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 8032 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 8033 Overflow = DAG.getSetCC(dl, SetCCVT, 8034 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 8035 dl, VT, Result, ShiftAmt), 8036 LHS, ISD::SETNE); 8037 return true; 8038 } 8039 } 8040 8041 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 8042 if (VT.isVector()) 8043 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 8044 VT.getVectorNumElements()); 8045 8046 SDValue BottomHalf; 8047 SDValue TopHalf; 8048 static const unsigned Ops[2][3] = 8049 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 8050 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 8051 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 8052 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8053 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 8054 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 8055 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 8056 RHS); 8057 TopHalf = BottomHalf.getValue(1); 8058 } else if (isTypeLegal(WideVT)) { 8059 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 8060 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 8061 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 8062 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 8063 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 8064 getShiftAmountTy(WideVT, DAG.getDataLayout())); 8065 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 8066 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 8067 } else { 8068 if (VT.isVector()) 8069 return false; 8070 8071 // We can fall back to a libcall with an illegal type for the MUL if we 8072 // have a libcall big enough. 8073 // Also, we can fall back to a division in some cases, but that's a big 8074 // performance hit in the general case. 8075 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 8076 if (WideVT == MVT::i16) 8077 LC = RTLIB::MUL_I16; 8078 else if (WideVT == MVT::i32) 8079 LC = RTLIB::MUL_I32; 8080 else if (WideVT == MVT::i64) 8081 LC = RTLIB::MUL_I64; 8082 else if (WideVT == MVT::i128) 8083 LC = RTLIB::MUL_I128; 8084 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 8085 8086 SDValue HiLHS; 8087 SDValue HiRHS; 8088 if (isSigned) { 8089 // The high part is obtained by SRA'ing all but one of the bits of low 8090 // part. 8091 unsigned LoSize = VT.getFixedSizeInBits(); 8092 HiLHS = 8093 DAG.getNode(ISD::SRA, dl, VT, LHS, 8094 DAG.getConstant(LoSize - 1, dl, 8095 getPointerTy(DAG.getDataLayout()))); 8096 HiRHS = 8097 DAG.getNode(ISD::SRA, dl, VT, RHS, 8098 DAG.getConstant(LoSize - 1, dl, 8099 getPointerTy(DAG.getDataLayout()))); 8100 } else { 8101 HiLHS = DAG.getConstant(0, dl, VT); 8102 HiRHS = DAG.getConstant(0, dl, VT); 8103 } 8104 8105 // Here we're passing the 2 arguments explicitly as 4 arguments that are 8106 // pre-lowered to the correct types. This all depends upon WideVT not 8107 // being a legal type for the architecture and thus has to be split to 8108 // two arguments. 8109 SDValue Ret; 8110 TargetLowering::MakeLibCallOptions CallOptions; 8111 CallOptions.setSExt(isSigned); 8112 CallOptions.setIsPostTypeLegalization(true); 8113 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 8114 // Halves of WideVT are packed into registers in different order 8115 // depending on platform endianness. This is usually handled by 8116 // the C calling convention, but we can't defer to it in 8117 // the legalizer. 8118 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 8119 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8120 } else { 8121 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 8122 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8123 } 8124 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 8125 "Ret value is a collection of constituent nodes holding result."); 8126 if (DAG.getDataLayout().isLittleEndian()) { 8127 // Same as above. 8128 BottomHalf = Ret.getOperand(0); 8129 TopHalf = Ret.getOperand(1); 8130 } else { 8131 BottomHalf = Ret.getOperand(1); 8132 TopHalf = Ret.getOperand(0); 8133 } 8134 } 8135 8136 Result = BottomHalf; 8137 if (isSigned) { 8138 SDValue ShiftAmt = DAG.getConstant( 8139 VT.getScalarSizeInBits() - 1, dl, 8140 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 8141 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 8142 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 8143 } else { 8144 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 8145 DAG.getConstant(0, dl, VT), ISD::SETNE); 8146 } 8147 8148 // Truncate the result if SetCC returns a larger type than needed. 8149 EVT RType = Node->getValueType(1); 8150 if (RType.bitsLT(Overflow.getValueType())) 8151 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 8152 8153 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 8154 "Unexpected result type for S/UMULO legalization"); 8155 return true; 8156 } 8157 8158 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 8159 SDLoc dl(Node); 8160 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8161 SDValue Op = Node->getOperand(0); 8162 EVT VT = Op.getValueType(); 8163 8164 if (VT.isScalableVector()) 8165 report_fatal_error( 8166 "Expanding reductions for scalable vectors is undefined."); 8167 8168 // Try to use a shuffle reduction for power of two vectors. 8169 if (VT.isPow2VectorType()) { 8170 while (VT.getVectorNumElements() > 1) { 8171 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8172 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 8173 break; 8174 8175 SDValue Lo, Hi; 8176 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 8177 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 8178 VT = HalfVT; 8179 } 8180 } 8181 8182 EVT EltVT = VT.getVectorElementType(); 8183 unsigned NumElts = VT.getVectorNumElements(); 8184 8185 SmallVector<SDValue, 8> Ops; 8186 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 8187 8188 SDValue Res = Ops[0]; 8189 for (unsigned i = 1; i < NumElts; i++) 8190 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 8191 8192 // Result type may be wider than element type. 8193 if (EltVT != Node->getValueType(0)) 8194 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 8195 return Res; 8196 } 8197 8198 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 8199 SDLoc dl(Node); 8200 SDValue AccOp = Node->getOperand(0); 8201 SDValue VecOp = Node->getOperand(1); 8202 SDNodeFlags Flags = Node->getFlags(); 8203 8204 EVT VT = VecOp.getValueType(); 8205 EVT EltVT = VT.getVectorElementType(); 8206 8207 if (VT.isScalableVector()) 8208 report_fatal_error( 8209 "Expanding reductions for scalable vectors is undefined."); 8210 8211 unsigned NumElts = VT.getVectorNumElements(); 8212 8213 SmallVector<SDValue, 8> Ops; 8214 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 8215 8216 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8217 8218 SDValue Res = AccOp; 8219 for (unsigned i = 0; i < NumElts; i++) 8220 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 8221 8222 return Res; 8223 } 8224 8225 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 8226 SelectionDAG &DAG) const { 8227 EVT VT = Node->getValueType(0); 8228 SDLoc dl(Node); 8229 bool isSigned = Node->getOpcode() == ISD::SREM; 8230 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 8231 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 8232 SDValue Dividend = Node->getOperand(0); 8233 SDValue Divisor = Node->getOperand(1); 8234 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 8235 SDVTList VTs = DAG.getVTList(VT, VT); 8236 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 8237 return true; 8238 } else if (isOperationLegalOrCustom(DivOpc, VT)) { 8239 // X % Y -> X-X/Y*Y 8240 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 8241 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 8242 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 8243 return true; 8244 } 8245 return false; 8246 } 8247 8248 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 8249 SelectionDAG &DAG) const { 8250 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 8251 SDLoc dl(SDValue(Node, 0)); 8252 SDValue Src = Node->getOperand(0); 8253 8254 // DstVT is the result type, while SatVT is the size to which we saturate 8255 EVT SrcVT = Src.getValueType(); 8256 EVT DstVT = Node->getValueType(0); 8257 8258 unsigned SatWidth = Node->getConstantOperandVal(1); 8259 unsigned DstWidth = DstVT.getScalarSizeInBits(); 8260 assert(SatWidth <= DstWidth && 8261 "Expected saturation width smaller than result width"); 8262 8263 // Determine minimum and maximum integer values and their corresponding 8264 // floating-point values. 8265 APInt MinInt, MaxInt; 8266 if (IsSigned) { 8267 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth); 8268 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth); 8269 } else { 8270 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth); 8271 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth); 8272 } 8273 8274 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 8275 // libcall emission cannot handle this. Large result types will fail. 8276 if (SrcVT == MVT::f16) { 8277 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 8278 SrcVT = Src.getValueType(); 8279 } 8280 8281 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8282 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8283 8284 APFloat::opStatus MinStatus = 8285 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 8286 APFloat::opStatus MaxStatus = 8287 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 8288 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 8289 !(MaxStatus & APFloat::opStatus::opInexact); 8290 8291 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 8292 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 8293 8294 // If the integer bounds are exactly representable as floats and min/max are 8295 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 8296 // of comparisons and selects. 8297 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 8298 isOperationLegal(ISD::FMAXNUM, SrcVT); 8299 if (AreExactFloatBounds && MinMaxLegal) { 8300 SDValue Clamped = Src; 8301 8302 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 8303 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 8304 // Clamp by MaxFloat from above. NaN cannot occur. 8305 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 8306 // Convert clamped value to integer. 8307 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 8308 dl, DstVT, Clamped); 8309 8310 // In the unsigned case we're done, because we mapped NaN to MinFloat, 8311 // which will cast to zero. 8312 if (!IsSigned) 8313 return FpToInt; 8314 8315 // Otherwise, select 0 if Src is NaN. 8316 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8317 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 8318 ISD::CondCode::SETUO); 8319 } 8320 8321 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 8322 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 8323 8324 // Result of direct conversion. The assumption here is that the operation is 8325 // non-trapping and it's fine to apply it to an out-of-range value if we 8326 // select it away later. 8327 SDValue FpToInt = 8328 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 8329 8330 SDValue Select = FpToInt; 8331 8332 // If Src ULT MinFloat, select MinInt. In particular, this also selects 8333 // MinInt if Src is NaN. 8334 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 8335 ISD::CondCode::SETULT); 8336 // If Src OGT MaxFloat, select MaxInt. 8337 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 8338 ISD::CondCode::SETOGT); 8339 8340 // In the unsigned case we are done, because we mapped NaN to MinInt, which 8341 // is already zero. 8342 if (!IsSigned) 8343 return Select; 8344 8345 // Otherwise, select 0 if Src is NaN. 8346 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8347 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 8348 } 8349