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