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