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