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