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